第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

Go - 附加到結(jié)構(gòu)中的切片

Go - 附加到結(jié)構(gòu)中的切片

Go
狐的傳說 2021-06-18 22:01:09
我正在嘗試實(shí)現(xiàn) 2 個(gè)簡單的結(jié)構(gòu),如下所示: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))}我究竟做錯(cuò)了什么?我只想在框結(jié)構(gòu)上調(diào)用 addItem 方法并傳入一個(gè)項(xiàng)目
查看完整描述

3 回答

?
有只小跳蛙

TA貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超8個(gè)贊

嗯...這是人們在 Go 中附加到切片時(shí)最常見的錯(cuò)誤。您必須將結(jié)果分配回切片。


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

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

    return box.Items

}

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


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

TA貢獻(xiàn)1872條經(jīng)驗(yàn) 獲得超4個(gè)贊

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


查看完整回答
反對 回復(fù) 2021-06-21
?
Qyouu

TA貢獻(xiàn)1786條經(jīng)驗(yàn) 獲得超11個(gè)贊

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


擺脫 return 語句,因?yàn)樵摲椒ū徽{(diào)用以獲取指向結(jié)構(gòu)的指針,因此切片會自動修改。

無需初始化空切片并將其分配給結(jié)構(gòu)

    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)

    }


查看完整回答
反對 回復(fù) 2021-06-21
  • 3 回答
  • 0 關(guān)注
  • 240 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號