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