去奇怪的行为 - 变量没有正确递增

Mar*_*ace 1 go

我有以下代码,如果它不存在,则向切片添加新元素.如果它确实存在,那么qty属性应该增加现有元素而不是添加新元素:

package main

import (
    "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
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是qty永远不会正确递增.它总是以1结尾,在提供的例子中它应该是3.

我已经调试了代码,看起来确实达到了增量部分,但是值并不是持久存在于项目中.

这有什么不对?

Shu*_*hya 5

您正在递增Qtythe的副本,box.BoxItems因为range将生成切片中元素的副本.看这个例子.

所以,in for _, item := range box.BoxItems,item是box.BoxItems中元素的副本.

将你的循环改为

for i := 0; i < len(box.BoxItems); i++ {
    if box.boxItems[i].Id == boxItem.Id {
         box.boxItems[i].Qty++
         return box.BoxItems[i]
    }
}
Run Code Online (Sandbox Code Playgroud)

操场