4 ms·
Lots of currently allowed map keys can be mutated such as structs or arrays. Let whatever happens when you mutate them (what does happen?) happen also for slice
by omaranto 7y ago
Lots of currently allowed map keys can be mutated such as structs or arrays. Let whatever happens when you mutate them (what does happen?) happen also for slices.
- ainar-g 7y agoUhm, no, they cannot be mutated. If you use a structure with two integers as a key and then change one of these integers, then you have a new value, and a new key, just like with integers.
- omaranto 7y agoThat didn't quite clear up for me what happens when you mutate keys, so I ran a quick experiment. It seems like maybe the map stores a copy of the key, as the map doesn't "see the mutation". package main import "fmt" func main() { x := [2]int{1, 2} m := make(map[[2]int]int) m[x] = 5 fmt.Println(m[x]) x[1] = 3 fmt.Println(m[x], m[[2]int{1, 2}], m[[2]int{1, 3}]) for k, v := range m { fmt.Println(k, v) } } This prints: 5 0 5 0 [1 2] 5 I'd be perfectly happy if slices were allowed as keys with the same semantics as arrays...