分享
golang将interface{}转换为struct
lit10050528 · · 40590 次点击 · · 开始浏览这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。
项目中需要用到golang的队列,container/list,需要放入的元素是struct,但是因为golang中list的设计,从list中取出时的类型为interface{},所以需要想办法把interface{}转换为struct。
这里需要用到interface assertion,具体操作见下面代码:
1 package main 2 3 import ( 4 "container/list" 5 "fmt" 6 "strconv" 7 ) 8 9 type People struct { 10 Name string 11 Age int 12 } 13 14 func main() { 15 // Create a new list and put some numbers in it. 16 l := list.New() 17 l.PushBack(People{"zjw", 1}) 18 19 // Iterate through list and print its contents. 20 e := l.Front() 21 p, ok := (e.Value).(People) 22 if ok { 23 fmt.Println("Name:" + p.Name) 24 fmt.Println("Age:" + strconv.Itoa(p.Age)) 25 } else { 26 fmt.Println("e is not an People") 27 } 28 }
有疑问加站长微信联系(非本文作者)
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
关注微信40590 次点击
下一篇:golang初始化结构体数组
添加一条新回复
(您需要 后才能回复 没有账号 ?)
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码` - 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传
收入到我管理的专栏 新建专栏
项目中需要用到golang的队列,container/list,需要放入的元素是struct,但是因为golang中list的设计,从list中取出时的类型为interface{},所以需要想办法把interface{}转换为struct。
这里需要用到interface assertion,具体操作见下面代码:
1 package main 2 3 import ( 4 "container/list" 5 "fmt" 6 "strconv" 7 ) 8 9 type People struct { 10 Name string 11 Age int 12 } 13 14 func main() { 15 // Create a new list and put some numbers in it. 16 l := list.New() 17 l.PushBack(People{"zjw", 1}) 18 19 // Iterate through list and print its contents. 20 e := l.Front() 21 p, ok := (e.Value).(People) 22 if ok { 23 fmt.Println("Name:" + p.Name) 24 fmt.Println("Age:" + strconv.Itoa(p.Age)) 25 } else { 26 fmt.Println("e is not an People") 27 } 28 }