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)

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

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)
}
- 3 回答
- 0 關注
- 241 瀏覽
添加回答
舉報