go - Why do I get a "cannot assign" error when setting value to a struct as a value in a map? -




this question has answer here:

new go. encountered error , have had no luck finding cause or rationale it:

if create struct, can assign , re-assign 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 struct 1 value in 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 cannot assign p["hm"].age. that's it, no other info. http://play.golang.org/p/vrlsitd4ep

i found way around - creating incrementage func on person, can called , result assigned map key, eg p["hm"] = p["hm"].incrementage().

but, question is, reason "cannot assign" error, , why shouldn't allowed assign struct value directly?

p["hm"] isn't quite regular addressable value: hashmaps can grow @ runtime, , values moved around in memory, , old locations become outdated. if values in maps treated regular addressable values, internals of map implementation exposed.

so, instead, p["hm"] different thing called "map index expression" in spec; if search spec phrase "index expression" you'll see can things them, read them, assign them, , use them in increment/decrement expressions (for numeric types). can't everything. have chosen implement more special cases did, i'm guessing didn't keep things simple.

your approach seems here--you change regular assignment, 1 of specifically-allowed operations. approach (maybe larger structs want avoid copying around?) make map value regular old pointer can modify underlying object through:

package main  import "fmt" 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 += 1   fmt.printf("age: %d\n", p["hm"].age) } 




wiki

Comments

Popular posts from this blog

Asterisk AGI Python Script to Dialplan does not work -

python - Read npy file directly from S3 StreamingBody -

kotlin - Out-projected type in generic interface prohibits the use of metod with generic parameter -