目前在学习golang,主要的方法就是刷LeetCode。不过还是遇到些问题,不少竟然都是语法错误,有点无语。
近期遇到的一个 cannot assign to struct field allData['a'].eq in map
先记录一下遇到的初始化复杂数据结构的问题,如果像下面这些代码这么写,编译器会报错cannot assign to struct field allData['a'].eq in mapgo
type Relation struct {
eq map[byte]bool
ne map[byte]bool
}
var allData = make(map[byte]Relation)
allData['a'] = Relation{}
allData['a'].eq = make(map[byte]bool)
如果写成下面在我看来等价的形式就没问题,直觉上很奇怪
type Relation struct {
eq map[byte]bool
ne map[byte]bool
}
var allData = make(map[byte]Relation)
a := Relation{}
a.eq = map[byte]bool{e2: true}
allData['a'] = a
或者下面的写法也可以
allData[e1] = Relation{map[byte]bool{}, map[byte]bool{}}
allData[e1].eq['b'] = true
看了些关于这个错误的解释、Go maps in action - The Go Blog 、github上的issueproposal: spec: cannot assign to a field of a map element directly: m["foo"].f = x · Issue #3117 · golang/go 以及语言规范中关于赋值部分,模糊有点感觉大体能理解,但是感觉是没处理好的一个地方。
在go中map是个指针类型,在这种情况下不能直接赋值,下面这个例子更清晰,貌似这种写法更好一些
allData[e1] = Relation{map[byte]bool{}, map[byte]bool{}}
if thisData, ok := allData[e1]; ok {
thisData.eq = map[byte]bool{}
allData[e1] = thisData
} else {
// 初始化该元素
}