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)

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

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)
}
- 3 回答
- 0 關(guān)注
- 240 瀏覽
添加回答
舉報(bào)