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

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

更新傳遞給函數(shù)的結(jié)構(gòu)中的切片

更新傳遞給函數(shù)的結(jié)構(gòu)中的切片

Go
明月笑刀無情 2022-04-20 20:42:25
需要幫助了解如何更新包含在結(jié)構(gòu)中并傳遞給函數(shù)的切片。函數(shù) addBookToShelfInLibrary(l *library,shelfid int, b book) - 將圖書館作為輸入,嘗試將書籍添加到 id = shelfid 的書架(作為參數(shù)傳遞)。該函數(shù)附加到書籍?dāng)?shù)組并將其分配給書籍?dāng)?shù)組。我錯(cuò)過了什么?在代碼運(yùn)行結(jié)束時(shí),我希望這些書包含兩本書,“harrypotter”,“bible”,但我只看到一本書,即 harrypotter。另外,我正在傳遞一個(gè)指向庫(kù)的指針,但我認(rèn)為在這種情況下這并不重要。操場(chǎng)代碼:- https://play.golang.org/p/JrjtLSj-jHIfunc main() {    lib := library{        shelves: []shelf{            {                id: 1,                books: []book{                    {name: "harrypotter"},                },            },        },    }    addBookToShelfInLibrary(&lib, 1, book{name: "bible"})    fmt.Printf("%v", lib)}type library struct {    shelves []shelf}type shelf struct {    id    int    books []book}type book struct {    name string}func addBookToShelfInLibrary(l *library, shelfid int, b book) {    for _, s := range (*l).shelves {        if s.id == shelfid {            //found shelf, add book            s.books = append(s.books, b)        }    }}
查看完整描述

1 回答

?
www說

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

在本聲明中:


s := range (*l).shelves 

該變量s是切片元素的副本。稍后對(duì) append 的調(diào)用會(huì)修改此副本,即非切片元素。更改代碼以修改切片元素:


func addBookToShelfInLibrary(l *library, shelfid int, b book) {

    for i := range l.shelves {

        s := &l.shelves[i]

        if s.id == shelfid {

            //found shelf, add book

            s.books = append(s.books, b)

        }

    }

}

另一種方法是使用指向架子的指針:


type library struct {

    shelves []*shelf

}


lib := library{

    shelves: []*shelf{

        {

 ...

所有其他代碼保持不變。


查看完整回答
反對(duì) 回復(fù) 2022-04-20
  • 1 回答
  • 0 關(guān)注
  • 128 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號(hào)

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