golang将interface{}转换为struct

项目中需要用到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 }

 

posted @ 2017-12-28 22:42  冷冰若水  阅读(8396)  评论(0编辑  收藏  举报