golang将interface{}转换为struct
2017-12-28 22:42
267 查看
项目中需要用到golang的队列,container/list,需要放入的元素是struct,但是因为golang中list的设计,从list中取出时的类型为interface{},所以需要想办法把interface{}转换为struct。
这里需要用到interface assertion,具体操作见下面代码:
这里需要用到interface assertion,具体操作见下面代码:
package main import ( "container/list" "fmt" "strconv" ) type People struct { Name string Age int } func main() { // Create a new list and put some numbers in it. l := list.New() l.PushBack(People{"zjw", 1}) // Iterate through list and print its contents. e := l.Front() p, ok := (e.Value).(People) if ok { fmt.Println("Name:" + p.Name) fmt.Println("Age:" + strconv.Itoa(p.Age)) } else { fmt.Println("e is not an People") } }
相关文章推荐
- golang里如何将一个struct指针转换成slice
- Golang 父子对象与JSON互相转换以及struct结构体内部的反引号该如何定义字段编码生成json字符串的写法
- golang的interface到其他类型的数据转换
- golang 之 bson 与 struct 转换
- golang--从类型转换角度看interface
- 工作随笔——Golang interface 转换成其他类型
- Golang 奇葩的时间包之Json与struct对象之间互相转换,JsonDate和JsonTime自定义类型如何实现json编码和解码(二)
- golang中struct和interface的基础使用教程
- golang--从类型转换角度看interface
- golang中interface{}转为struct
- golang学习之interface与其它类型转换
- golang中struct和[]byte的相互转换示例
- golang struct 实现 interface的方法
- golang中struct和[]byte的相互转换
- golang之interface
- 接口(interface)与类(class)的实例互相转换
- GoLang中 json、map、struct 之间的相互转化
- Golang如何实现任意进制转换的方法示例
- golang中struct成员变量的标签(Tag)说明和获取方式
- class、interface、struct的差别