需要幫助了解如何更新包含在結(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{
{
...
所有其他代碼保持不變。
- 1 回答
- 0 關(guān)注
- 128 瀏覽
添加回答
舉報(bào)
0/150
提交
取消