Go类型断言demo

package main

import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"github.com/unknwon/com"
) //空接口
func test1() {
a := make(map[string]interface{}, 20)
a["name"] = "haha"
a["age"] = 20
a["merried"] = true
a["hobby"] = []string{"喝", "跳", "rap"}
fmt.Printf("type:%T v:%#v\n", a["hobby"],a["hobby"])
v,ok := a["hobby"].([]string)
if(!ok){
fmt.Println("type is not map.") //type:[]string v:[]string{"喝", "跳", "rap"}
} fmt.Println(v[0]) //喝 } //接口作为函数的参数
func test2(a interface{}) {
fmt.Printf("type:%T value:%v \n", a, a)
} type resParamData struct {
Code int `json:"code"`
Msg string `json:"Msg"`
Data interface{} //方法一
}
type userinfo struct {
Name string `json:"name"`
Age int `json:"age"`
} func test3() {
var m = make(map[string]interface{}, 0)
m["name"] = "test"
m["age"] = 20
var res resParamData
res.Code = 200
res.Msg = "ok"
res.Data = m fmt.Println(res.Data)
value, ok := res.Data.(map[string]interface{})
if !ok {
fmt.Println("It's not ok for type Order")
return
}
fmt.Println("The value is ", value["name"])
fmt.Println("The value is ", value["age"])
fmt.Printf("type:%T value:%v\n", value["age"], value["age"]) }
func test4() {
var uinfo = userinfo{
Name: "lisi",
Age: 18,
}
var resdata resParamData
resdata.Code = 200
resdata.Msg ="ok"
resdata.Data = uinfo
fmt.Println(resdata.Data)
value, ok := resdata.Data.(userinfo)
if !ok {
fmt.Println("It's not ok for type Order")
return
}
fmt.Println("The value is ", value.Name)
fmt.Println("The value is ", value.Age)
fmt.Printf("type:%T value:%v\n", value.Name, value.Name)
fmt.Printf("type:%T value:%v\n", value.Age, value.Age) }
type PostresData2 struct {
Data interface{} //方法一
Errmsg string `json:"errmsg"`
Errno int `json:"errno"`
}
func test5() {
var d PostresData2
url := "https://api.ibanana.club/select/major/list_by_key?page=1&row=10&major_name=工程"
res := SetGet(url)
_ = json.Unmarshal([]byte(res), &d)
fmt.Println(1111111111)
fmt.Printf("type:%T value:%#v \n", d, d)
fmt.Printf("type:%T value:%#v \n", d.Errno, d.Errno)
fmt.Printf("type:%T value:%#v \n", d.Data, d.Data)
value,ok:=d.Data.([]interface {})
if !ok {
fmt.Println("It's not ok for type major")
return
}
for _,v:=range value{
m,ok:=v.(map[string]interface {})
if !ok {
fmt.Println("It's not ok for type m")
return
}
id:=com.StrTo(com.ToStr(m["id"])).MustInt64()
fmt.Printf("type:%T value:%v\n",id, id) //type:int64 value:20
fmt.Printf("type:%T value:%v\n", m["major_name"], m["major_name"]) //type:string value:交通工程
//改变期值
if(id==19){
m["id"]=100
m["major_name"]="edit value22"
}
}
fmt.Println("GetTest")
fmt.Println(d)
//httpext.SuccessExt(ctx, d)
} func main() {
//test5()
//test4()
//test3()
test1()
//a := 12
//test2(a)
//test2(nil)
//test2(false)
}
// Get ... 发送请求 ...
// url: 请求地址
// response: 请求返回的内容
func SetGet(url string) string { // 超时时间:5秒
client := &http.Client{Timeout: 5 * time.Second}
resp, err := client.Get(url)
if err != nil {
panic(err)
}
defer resp.Body.Close()
var buffer [512]byte
result := bytes.NewBuffer(nil)
for {
n, err := resp.Body.Read(buffer[0:])
result.Write(buffer[0:n])
if err != nil && err == io.EOF {
break
} else if err != nil {
panic(err)
}
} return result.String()
}

test5接口的反参

{
"code": 200,
"data": {
"Data": [
{
"id": 100,
"major_name": "edit value22"
},
{
"id": 20,
"major_name": "交通工程"
},
{
"id": 22,
"major_name": "交通管理工程"
},
{
"id": 23,
"major_name": "交通设备与控制工程"
},
{
"id": 46,
"major_name": "信息工程"
},
{
"id": 50,
"major_name": "假肢矫形工程"
},
{
"id": 53,
"major_name": "光电信息科学与工程"
},
{
"id": 63,
"major_name": "农业工程"
},
{
"id": 64,
"major_name": "农业建筑环境与能源工程"
},
{
"id": 66,
"major_name": "农业水利工程"
}
],
"errmsg": "ok",
"errno": 200
},
"msg": "ok"
}

Go类型断言demo的更多相关文章

  1. golang 类型断言的学习

    在php中有一个 serialize() 函数 可以把数组序列化成字符串进行存储和传输 如果想反序列化这种字符串,在php中只需要一个简单的unserialize() 函数就可以完成了.但是在gola ...

  2. golang学习笔记:Interface类型断言详情

    原文链接:https://www.2cto.com/kf/201712/703563.html 1. 用于判断变量类型 demo如下: switch t := var.(type){ case str ...

  3. GO语言总结(5)——类型转换和类型断言

    上一篇博客介绍了Go语言的数组和切片——GO语言总结(4)——映射(Map),本篇博客介绍Go语言的类型转换和类型断言 由于Go语言不允许隐式类型转换.而类型转换和类型断言的本质,就是把一个类型转换到 ...

  4. Go的类型断言解析

    经常地我们对一个接口值的动态类型是不确定的,如方法的形参为接口类型时,此时就需要检验它是否符合我们需要的类型.类型断言是一个使用在接口值上的操作.断言类型的语法:x.(T),这里x表示一个接口的类型, ...

  5. golang类型断言

    一.介绍 类型断言,由于接口是一般类型,不知道具体类型,如果要转成具体类型,就需要使用类型断言 例子: package main import "fmt" func main(){ ...

  6. [Go] golang类型断言

    类型断言有点像向下转型,接口类型转到具体的实现实例类型上类型断言是一个使用在接口值上的操作.语法上它看起来像x.(T)被称为断言类型,这里x表示一个接口的类型和T表示一个类型 package main ...

  7. Golang的类型断言

    类型断言即判断一个变量是不是某个类型的实例,这个经常用在判断接口的类型,基本的格式: y, ok := x.(type) 上面的语句用于判断变量x是不是type类型,有两种结果: x是type类型的变 ...

  8. go语言之进阶篇通过switch实现类型断言

    1.通过switch实现类型断言 示例: package main import "fmt" type Student struct { name string id int } ...

  9. go语言之进阶篇通过if实现类型断言

    1.通过if实现类型断言 示例: package main import "fmt" type Student struct { name string id int } func ...

  10. Go语言的类型转换和类型断言

    https://my.oschina.net/chai2010/blog/161418 https://studygolang.com/articles/9335  类型转换.类型断言和类型切换 ht ...

随机推荐

  1. Flume入门操作

    十一.Flume 1)开启Flume的监控端口 bin/flume-ng agent -c conf/ -n a1 -f job/flume-netcat-logger.conf -Dflume.ro ...

  2. 一文弄懂java中的Queue家族

    目录 简介 Queue接口 Queue的分类 BlockingQueue Deque TransferQueue 总结 java中Queue家族简介 简介 java中Collection集合有三大家族 ...

  3. OpenHarmony有氧拳击之设备端开发

    一.简介 在一个风和日丽,阳光明媚的下午,码农们都像往常一样正在专注地码代码.突然前面的小哥哥站起来,手握开发板,来回出拳.这是怎么回事? 原来这是一款拳击互动游戏,本文将带你一同解开其中的奥秘.开发 ...

  4. 9. Complex Vectors and Matrices

    9.1 Real versus Complex R= line of all real numbers (\(-\infty < x < \infty\)) \(\longleftrigh ...

  5. std::thread 五:打包任务(packaged_task)

    #include <iostream> #include <thread> #include <mutex> #include <list> #incl ...

  6. linux 允许root 用户登录(旧)

    前言 旧博客迁移的内容 正文 vi /etc/ssh/sshd_config 将PermitRootLogin值改yes service sshd restart

  7. DBJ,DB,CJJ,CECS 标准区别及全套下载教程

    DBJ DBJ开头的标准是地方建筑标准:D--地方. B--标准. J--建筑. <中华人民共和国标准化法>将中国标准分为国家标准.行业标准.地方标准(DB).企业标准(Q/)四级.地方标 ...

  8. MAC Book: Operation not permitted

    背景: 最近清理系统上的一些无用的文件后,为了release出可用空间,所以还要把.Trash目录下的文件清理才真正清理完,但是ls 查看该目录时发现一直报"operation not pe ...

  9. ORA-29277:invalid SMTP operation

    ORA-29277:invalid SMTP operation 邮件发送的时候出现报错 ORA-29277:invalid SMTP operation 官方解释就很简单 但是实际上重试是不行的,几 ...

  10. eclipse tomcat的一些错误

    eclipse tomcat运行错误 错误提示: Server Tomcat v7.0 Server at localhost was unable to start within 45 second ...