On Wednesday, 7 October 2020 08:05:39 UTC+1, Amnon wrote: > > Go generally ensures that zero values are useful. > > So a zero slice allows us to append to it, without having to do any > special initialization. > > Not exactly. Appending to a slice always creates a *new* slice value:
s2 := append(s1, v) (Aside: the new slice may or may not share the same backing store as the original slice, depending on whether s1's backing is suitable or not. But s2 is always a new *value*) It becomes clear when you realise that a slice value is really a hidden struct, in pseudo-code something like: struct { backing *T cap int len int } The zero slice value is this struct initialized to all zeros. This gives a null pointer (i.e. no backing store), and a zero cap and len. There's very little you can do with this value, except determine that its length is zero. So why are maps different? Why is it necessary to make a map, before it can > be assigned to? > Is there any use case where a zero map which can not be assigned to is > useful? > Just like the zero slice, the zero map can be read from, and it returns len() of zero. Reading any key from it will return zero value. Like the slice, the map is also a struct which contains a pointer. However for simplicity and efficiency reasons, you add to a map by mutating it, not by creating a new map. This means that the map must have been initialized, so that its internal pointer points to a valid data structure, before you can update it. If you want appending to a map to work the same way as appending to a slice, you can wrap it yourself easily enough: https://play.golang.org/p/6Q9EtMVUsea -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/a1d29afc-4307-4b32-b4e4-431fc5d965cao%40googlegroups.com.