簡體   English   中英

在 go 中創建一個包含列表類型的結構

[英]Creating a struct that contains list types in go

我創建了一個結構,這個結構包含兩個列表類型。 當我嘗試實例化我的結構時,我收到錯誤

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()}

list.New() 返回一個指針*List ,而 myStruct 將其字段聲明為List

func New() *List

消息和用戶應該是 *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()}

您正在創建錯誤的結構,因為根據listNew()方法返回列表的指針類型,並且您在沒有指針的結構中創建了list

func New() *List

因此,根據文檔,您需要創建如下結構:

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

去游樂場

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM