Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

It should be noted that slices and maps are completely opposite ends of how they behave in relation to nil in Go. A nil slice is just an empty slice, there is no operation you could do with one that will fail if done with the other. In contrast, a nil map doesn't support any operation whatsoever, it will panic on doing anything with it.



You're quite mistaken. You can use len() on both nil maps and slices, and it will return zero (as with empty ones). Panic occurs on both nil assignments. But then, access only panics on nil slices - nil maps produce the zero value. It's horrible.

https://go.dev/play/p/2KFOoJ0oyWB


Access on an empty slice would also panic because of out of bounds. So there’s no useful distinction there.

However, nil slices work just fine when calling append on them, while writing to a nil map in any way will panic.


Right, forgot that len() works on nil maps, and I was really not aware that reading from a nil map is not an error, that's crazy.

For the nil slice though what I said remains true: a nil slice is the same thing as an empty slice. Of course reading from or writing to its first element panics, given that it doesn't have any elements. The same would have happened if you had initialized it as `var ns []int = make([]int, 0)` or `ns := []int{}`.


Ah now I get it, yes you're right, they behave the same.

Ironically, just today I read that in the next release they will add some JSON annotation to distinguish nil slices (omitzero): https://tip.golang.org/doc/go1.24




Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: