golang将interface{}转换为struct

项目中须要用到golang的队列,container/list,须要放入的元素是struct,可是由于golang中list的设计,从list中取出时的类型为interface{},因此须要想办法把interface{}转换为struct。golang

这里须要用到interface assertion,具体操做见下面代码:post

 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 }