简体   繁体   中英

Creating a struct that contains list types in go

I have created a struct, this struct has contains two list types within it. When I try to instantiate my struct I receive the error

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

I am using the golang playground

The struct

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

Instantiating the struct

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

list.New() returns a pointer *List , while myStruct announce its fields as List .

func New() *List

messages and users should be *list.List

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

Another approach according to your need, u can just initialize the struct as below:

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

You are creating wrong struct because go, according to list package New() method returns pointer type of list and you created list in struct without pointer.

func New() *List

So, according to doc you need to created your struct like below:

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

Go Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM