计算Golang产品中广告系列的出现次数

时间:2018-04-06 12:19:37

标签: go

我有以下代码

    teasers := []*models.TeaserCount{}
    var teaser models.TeaserCount

    for _, product := range ProductResponse.Products {
        added := false
        if len(product.Campaign.Id) > 0 {
            if len(teasers) > 0 {
                for _, teaserCount := range teasers {
                    if teaserCount.Id == product.Campaign.Id {
                        fmt.Println(teaserCount.Id, teaserCount.Count+1)
                        teaserCount.Count++
                        added = true
                        break
                    }
                }

                if added == false {
                    teaser = models.TeaserCount{
                        Id:    product.Campaign.Id,
                        Count: 0,
                    }

                    teasers = append(teasers, &teaser)
                }
            } else {
                teaser = models.TeaserCount{
                    Id:    product.Campaign.Id,
                    Count: 0,
                }

                teasers = append(teasers, &teaser)
            }
        }
    }

我想要做的是计算每个广告系列在产品中出现的次数 我想拥有一系列对象,包括广告系列ID和出现次数

我得到的结果是数组中的每个单个对象都是相同的(最后一个通过追加添加)

怎么会这样,这种行为对我来说似乎很奇怪,也许这与指针有关?

1 个答案:

答案 0 :(得分:1)

您将附加一个指向本地循环变量的指针,该变量在每次迭代时都会发生变化:

// This pointer will always point to the current/last loop iteration value
teasers = append(teasers, &teaser)

您应该添加指向副本的指针:

temp := teaser
teasers = append(teasers, &temp)

或指向切片元素的指针:

for i, product := range ProductResponse.Products {
    // ...
    teasers = append(teasers, &ProductResponse.Products[i])

如果选择前者,则指针将指向专用于teasers的副本,而如果执行后者,则指针将指向原始切片的元素(表示该值是否为切片更改,将反映在teasers)。