我有以下代碼將一個新元素添加到一個切片(如果它不存在)。如果它確實存在,那么 qty 屬性應(yīng)該增加現(xiàn)有元素而不是添加新元素:package mainimport ( "fmt")type BoxItem struct { Id int Qty int}type Box struct { BoxItems []BoxItem}func (box *Box) AddBoxItem(boxItem BoxItem) BoxItem { // If the item exists already then increment its qty for _, item := range box.BoxItems { if item.Id == boxItem.Id { item.Qty++ return item } } // New item so append box.BoxItems = append(box.BoxItems, boxItem) return boxItem}func main() { boxItems := []BoxItem{} box := Box{boxItems} boxItem := BoxItem{Id: 1, Qty: 1} // Add this item 3 times its qty should be increased to 3 afterwards box.AddBoxItem(boxItem) box.AddBoxItem(boxItem) box.AddBoxItem(boxItem) fmt.Println(len(box.BoxItems)) // Prints 1 which is correct for _, item := range box.BoxItems { fmt.Println(item.Qty) // Prints 1 when it should print 3 }}問題是數(shù)量永遠不會正確增加。當它在提供的示例中應(yīng)該是 3 時,它總是以 1 結(jié)尾。我已經(jīng)調(diào)試了代碼,看起來確實達到了增量部分,但該值并未保留到項目中。這里有什么問題?
3 回答

開滿天機
TA貢獻1786條經(jīng)驗 獲得超13個贊
您正在增加Qty的副本,box.BoxItems因為range將產(chǎn)生切片中元素的副本。請參閱此示例。
所以,在for _, item := range box.BoxItems,item是在box.BoxItems元素的副本。
將您的循環(huán)更改為
for i := 0; i < len(box.BoxItems); i++ {
if box.boxItems[i].Id == boxItem.Id {
box.boxItems[i].Qty++
return box.BoxItems[i]
}
}
- 3 回答
- 0 關(guān)注
- 198 瀏覽
添加回答
舉報
0/150
提交
取消