您的位置:首页 > 编程语言 > Go语言

golang将interface{}转换为struct

2017-12-28 22:42 267 查看
项目中需要用到golang的队列,container/list,需要放入的元素是struct,但是因为golang中list的设计,从list中取出时的类型为interface{},所以需要想办法把interface{}转换为struct。

这里需要用到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")
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: