On Monday, May 6, 2013, Jingcheng Zhang wrote:
Hello gophers,
The codes cannot compile:
func main() {
m := make(map[int][2]int, 10)
m[0] = [2]int{1, 2}
m[0][1] = 3
println(m[0][1])
}
Result is:
>go run main.go
# command-line-arguments
.\main.go:6: cannot assign to m[0][1]
Why?
The elements inside a map are not addressable. This is because, if you store the address of an element in a map, that address might be invalidated at a later time if the element gets removed from the map or the map restructures itself internally. You cannot assign to unaddressable values. The one exception is assigning directly to map indexing expressions, so you can put stuff in a map. However, it doesn't let you assign to unaddressable expressions derived from map indexing expressions, hence the error. Plausibly the compiler could break these assignments into three steps: (1) copy the element out of the map, (2) update the copy, (3) overwrite the element in the map with the copy. However, Go tries not to be too magical, and hiding this three step process by making it look like a simple assignment would work against that.