New to Go. Encountered this error and have had no luck finding the cause or the rationale for it:
If I create a struct, I can obviously assign and re-assign the values no problem:
type Person struct {
name string
age int
}
func main() {
x := Person{"Andy Capp", 98}
x.age = 99
fmt.Printf("age: %d\n", x.age)
}
but if the struct is one value in a map:
type Person struct {
name string
age int
}
type People map[string]Person
func main() {
p := make(People)
p["HM"] = Person{"Hank McNamara", 39}
p["HM"].age = p["HM"].age + 1
fmt.Printf("age: %d\n", p["HM"].age)
}
I get cannot assign to p["HM"].age
. That's it, no other info. http://play.golang.org/p/VRlSItd4eP
I found a way around this - creating an incrementAge
func on Person, which can be called and the result assigned to the map key, eg p["HM"] = p["HM"].incrementAge()
.
But, my question is, what is the reason for this "cannot assign" error, and why shouldn't I be allowed to assign the struct value directly?
p["HM"]
isn't quite a regular pointer value, because the values in a map get moved around in memory, and the old locations become invalid, when the map grows. So you can't do all the operations on it that you could do on a regular pointer. Besides your solution (change it to an assignment, one of the allowed operations, which seems good here), another approach (maybe good for large objects?) is to make the map value a regular old pointer that you can modify the underlying object through: play.golang.org/p/n5C4CsKOAVp["HM"]
are scattered around the spec if you search for "index expression": you can read the value, assign a new whole value, delete, increment/decrement numeric values.*Person
at one point but I think I forgot to create the reference with&
- still getting used to this. thanks, make it an answer and I'd accept...[go] map cannot assign
search.