亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Go - 附加到結構中的切片

Go - 附加到結構中的切片

Go
狐的傳說 2021-06-18 22:01:09
我正在嘗試實現 2 個簡單的結構,如下所示:package mainimport (    "fmt")type MyBoxItem struct {    Name string}type MyBox struct {    Items []MyBoxItem}func (box *MyBox) AddItem(item MyBoxItem) []MyBoxItem {    return append(box.Items, item)}func main() {    item1 := MyBoxItem{Name: "Test Item 1"}    item2 := MyBoxItem{Name: "Test Item 2"}    items := []MyBoxItem{}    box := MyBox{items}    AddItem(box, item1)  // This is where i am stuck    fmt.Println(len(box.Items))}我究竟做錯了什么?我只想在框結構上調用 addItem 方法并傳入一個項目
查看完整描述

3 回答

?
有只小跳蛙

TA貢獻1824條經驗 獲得超8個贊

嗯...這是人們在 Go 中附加到切片時最常見的錯誤。您必須將結果分配回切片。


func (box *MyBox) AddItem(item MyBoxItem) []MyBoxItem {

    box.Items = append(box.Items, item)

    return box.Items

}

此外,您已經定義AddItem了*MyBox類型,因此將此方法稱為box.AddItem(item1)


查看完整回答
反對 回復 2021-06-21
?
守著一只汪

TA貢獻1872條經驗 獲得超4個贊

package main


import (

        "fmt"

)


type MyBoxItem struct {

        Name string

}


type MyBox struct {

        Items []MyBoxItem

}


func (box *MyBox) AddItem(item MyBoxItem) []MyBoxItem {

        box.Items = append(box.Items, item)

        return box.Items

}


func main() {


        item1 := MyBoxItem{Name: "Test Item 1"}


        items := []MyBoxItem{}

        box := MyBox{items}


        box.AddItem(item1)


        fmt.Println(len(box.Items))

}



輸出:


1


查看完整回答
反對 回復 2021-06-21
?
Qyouu

TA貢獻1786條經驗 獲得超11個贊

雖然這兩個答案都很好。還有兩個變化可以做,


擺脫 return 語句,因為該方法被調用以獲取指向結構的指針,因此切片會自動修改。

無需初始化空切片并將其分配給結構

    package main    


    import (

        "fmt"

    )


    type MyBoxItem struct {

        Name string

    }


    type MyBox struct {

        Items []MyBoxItem

    }


    func (box *MyBox) AddItem(item MyBoxItem) {

        box.Items = append(box.Items, item)

    }



    func main() {


        item1 := MyBoxItem{Name: "Test Item 1"}

        item2 := MyBoxItem{Name: "Test Item 2"}


        box := MyBox{}


        box.AddItem(item1)

        box.AddItem(item2)


        // checking the output

        fmt.Println(len(box.Items))

        fmt.Println(box.Items)

    }


查看完整回答
反對 回復 2021-06-21
  • 3 回答
  • 0 關注
  • 241 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號