3 ms·
Fixing the existing maps sounds a lot easier than adding generics. All that would be required is to allow slices as keys. If there is a concern about immutabili
by omaranto 7y ago
Fixing the existing maps sounds a lot easier than adding generics. All that would be required is to allow slices as keys. If there is a concern about immutability you could just say mutating a slice used as a key leads to undefined behavior.
- ainar-g 7y agoAFAIK, “undefined behaviour” is not a thing in Go The Language (there is some undefined behaviour in the Go The StdLib). The Go Specification[1] doesn't even contain the word “undefined”, and only has two instances of “unspecified”. I guess that if immutable slices became a thing, one would probably be able to use them as map keys. But so far the Go Team is very reluctant about adding immutability to the language. [1]: https://golang.org/ref/spec https://golang.org/ref/spec
- omaranto 7y agoLots 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...