无法在地图中分配对

时间:2016-07-06 18:16:12

标签: dictionary go

我的go程序中定义了以下对

type pair struct {
  a float64
  b float64
}

然后我创建了一张地图:

dictionary map[string]pair

我先添加一个元素:

dictionary["xxoo"] = pair{5.0, 2.0}

然后我试图这样做:

dictionary["xxoo"].b = 5.0  // try to change from 2.0 to 5.0

最后一行没有编译,它说"无法分配给它#34;

我想知道原因是什么?

3 个答案:

答案 0 :(得分:6)

为了给struct字段赋值,该结构必须是"可寻址"。可寻址性包含在语言规范的"Address Operators"部分中。

地图值不可寻址,以使地图实现能够根据需要自由地在内存中移动值。由于地图值不可寻址,因此您无法在值上使用选择器(.)运算符来指定结构字段。如果使用指针类型作为映射值,即map[string]*pair,则指针间接满足可寻址性要求。

dict := make(map[string]*pair)
dict["xxoo"] = &pair{5.0, 2.0}
dict["xxoo"].b = 5.0

如果您正在使用值,则需要通过赋值复制现有值,或者提供一个全新的值:

dict := make(map[string]pair)
dict["xxoo"] = pair{5.0, 2.0}

// copy the value, change one field, then reassign
p := dict["xxoo"]
p.b = 5.0
dict["xxoo"] = p

// or replace the value in full
dict["xxoo"] = pair{5.0, 5.0}

答案 1 :(得分:3)

由于here所述的原因,这是不合法的:

  

查询地图会提供存储项目的副本,因此没有分配给它的点。

建议的解决方法是:

var xxoo = dictionary["xxoo"]
xxoo.b = 5.0
dictionary["xxoo"] = xxoo

答案 2 :(得分:2)

在托马斯的回答中说这是禁止的。改为使用指针。

dict := map[string]*pair{}
dict["xxoo"] = &pair{5.0, 2.0}
fmt.Println(dict["xxoo"].b) // 2
dict["xxoo"].b = 5.0
fmt.Println(dict["xxoo"].b) // 5

https://play.golang.org/p/nEr_WrQOly