Hacker News new | ask | show | jobs
by songgao 2845 days ago
This old blog post has a pretty good explanation about how Go slice works: https://blog.golang.org/go-slices-usage-and-internals

Once you realize slices are just (pointer, length, capacity) structures, and the structure itself is copied by value, the first 2 WAT is pretty trivial.

2 comments

It's kind of broken that slices are immutable but maps aren't, and that reading a slice can panic but reading a map can't.
Reading from a nil slice and map feel consistent to me. If you read from a nil map you get the same result as reading a key that is not in a non-nil map (because that key is clearly not in the map because it's nil). Similarly, if you read from a nil slice you get the same result as reading an index that's not in the slice, an out of bounds access.
Trivial in isolation, but it is much harder to see the problem in a heap of source code. In general such "surprise moments" should be regarded seriously however it seems trivial in isolation.