4 ms·
>A map-based operation that's equivalent to "append" would be a (hypothetical) builtin function like "func assign(m map[K]V, key K, value V) map[K]V". But why
by nemothekid 5y ago
>A map-based operation that's equivalent to "append" would be a (hypothetical) builtin function like "func assign(m map[K]V, key K, value V) map[K]V".
But why isn't there an `assign` function? I've been writing Go for a long time, and from a design point of view, I really don't like append. It's magic, and as the OP has shown, it's trips up new programmers. If Go was consistent, there shouldn't be an append; but instead we got "generics for this one function". The problem isn't really `nil` that acts confusing (in this case), it's `append` acting like a function when it's really a magic compiler directive.
I personally think this criticism is a problem; zero-values, especially nil ones, can be a major footgun. I've had a couple experiences where a production service crashed because someone accidentally tried to use a nil interface even though they had already nil-checked it.
- morelisp 5y agoappend is the opposite of magic. it's exposing the details of a realloc when 99% of the time you want to keep the same binding. That's probably also why map doesn't have an equivalent; in the case of hash tables it's more like 99.999%.
- nemothekid 5y ago>append is the opposite of magic You cannot write the append function in pre-go 1.18. That is what I mean by magic. The reason it's given to you because it would be painful to build a function like append for every slice type. That's also why it gets to have blessed nil properties.
- morelisp 5y agoWell, you could, using unsafe. But you also couldn't write the index operator (without unsafe), and I don't think anyone would call that "magic". And in either case that has nothing to do with its treatment of nil. It would be more magic if it somehow updated a hidden pointer, like maps do. (And this has also been my experience teaching Go, people grasp quickly that slice length/cap is immutable but often forget that non-nil maps are mutable and always "by reference".)