gpt4 book ai didi

go - 无法分配给 mapMeasures[ts].Delta

转载 作者:行者123 更新时间:2023-12-01 21:13:42 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Accessing struct fields inside a map value (without copying)

(2 个回答)


1年前关闭。




我有一个类型:

type Measure struct {
Timestamp time.Time
Delta float64
}

我正在将一组度量值转换为以时间戳为键的 map :
func MeasuresToMap(measures []models.Measure) map[string]models.Measure {
mapMeasures := make(map[string]models.Measure, len(measures)) //
for _, measure := range measures {
mapMeasures[measure.Timestamp.Format(time.RFC3339)] = measure
}
return mapMeasures
}

我这样做:
mapMeasures := misc.MeasuresToMap(myMeasures)
for ts, _ := range mapMeasures {
mapMeasures[ts].Delta = 0
}

我得到:
Cannot assign to mapMeasures[ts].Delta

但我能做的:
for ts, measure := range mapMeasures {
measure.Delta = 0
mapMeasures[ts] = measure
}

这两个选项有什么区别,为什么我不能直接更新 Delta 字段?

最佳答案

你不能分配给你 的东西无法获取地址的。
mapMeasures[ts].Delta = 0 就是这种情况。 - 你不能取Measure的地址.以下是 Go Programming Language (A. Donovan, B. Kernighan) 书中关于获取 map 元素地址的内容:

One reason that we can’t take the address of a map element is that growing a map might cause rehashing of existing elements into new storage locations, thus potentially invalidating the address.



另一方面,当您执行 for ts, measure := range mapMeasures {...}您创建一个显式变量 measure因此您可以获取它的地址并分配给它。

关于go - 无法分配给 mapMeasures[ts].Delta,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61915269/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com