3 ms·
They mention it elsewhere in the post, but there are a few types that are essentially pointers but don't look like pointers. Slices, maps, interfaces, and chan
by ainar-g 4y ago
They mention it elsewhere in the post, but there are a few types that are essentially pointers but don't look like pointers. Slices, maps, interfaces, and channels (and also functions, but that isn't that important here). So you cannot just think that anything that doesn't have an asterisk is a copy.
Besides that, there is also the fact that slices share underlying array storage, and `append` doesn't make a copy unless there is still capacity, which means that you should be careful when working with subslices that get appended to.
https://go.dev/play/p/Iqd84_eAMNF https://go.dev/play/p/Iqd84_eAMNF
- wara23arish 4y agoI see! Thank you for the example that was helpful. I read through the example regarding the struct containing the map. I recently ran into that when working on something. slightly meta: So how can one evaluate whether that is a good decision or bad? Does forcing the programmer to use make explicitly for maps help prevent errors or is it tedious and better off having the zero value of map not cause errors?
- ainar-g 4y agoI actually agree with the author that nils are a massive pain in the arse most of the time, and that Go would be much better off without them. There is no precise, mathematical answer to your question, since it's always contingent on many things, but one way to evaluate a “correctness” of a design choice is the old adage that a good interface is hard to misuse. If your code can handle a nil map okay, and not requiring a non-nil map brings significant ergonomics advantages, you may not need to check it. Otherwise, I personally would err on the side of caution and design an API that either doesn't give the user a choice (i.e. creates the map itself) or returns an error if they provide invalid data.
- deleted 4y ago[deleted]