在go中创建一个包含列表类型的结构

时间:2019-01-02 08:50:27

标签: list go struct

我创建了一个结构,该结构中包含两个列表类型。当我尝试实例化我的结构时,我收到错误

cannot use list.New() (type *list.List) as type list.List in field value

我正在使用golang游乐场

结构

type myStruct struct {
    name string
    messages list.List
    users list.List
    lastUsed time.Time
}

实例化结构

var myVar = myStruct{"hello", list.New(), list.New(), time.Now()}

2 个答案:

答案 0 :(得分:3)

list.New()返回一个指针*List,而myStruct将其字段声明为List

  

func New()*列表

消息和用户应为* list.List

type myStruct struct {
    name string
    messages *list.List
    users *list.List
    lastUsed time.Time
}

根据您的需要的另一种方法,您可以按如下所示初始化结构:

var myVar = myStruct{"hello", *list.New(), *list.New(), time.Now()}

答案 1 :(得分:2)

您创建了错误的结构,因为根据listNew()方法,返回了列表的指针类型,并且您在没有指针的结构中创建了list

func New() *List

因此,根据文档,您需要按如下所示创建结构:

type myStruct struct {
    name string
    messages *list.List
    users *list.List
    lastUsed time.Time
}

https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/CapacityUnitCalculations.html

相关问题