Comment by culebron21
16 hours ago
> `value, keyExists := myMap[someKey]`
If I don't need the value, I have to do awkward tricks with this construct. like `if _, key_exists := my_may[key]; key_exists { ... }`.
Also, you can do `value := myMap[someKey]`, and it will just return a value or nil.
Also, if the map has arrays as elements, it will magically create one, like Python's defaultdict.
This construct (assigning from map subscript) is pure magic, despite all the claims, that there's none in Golang.
...And also: I guess the idea was to make the language minimal and easy to learn, hence primitives have no methods on them. But... after all OOP in limited form is there in Golang, exactly like in Rust. And I don't see the point why custom structs do have methods, and it's easier to use, but basic ones don't, and you have to go import packages.
Not that it's wrong. But it's not easier at all, and learning curve just moves to another place.
> Also, if the map has arrays as elements, it will magically create one, like Python's defaultdict.
Err, no Go doesn't do that. No insertion happens unless you explicitly assign to the key.
You're right. But it will return something: https://go.dev/play/p/Cz6aeGpURgo
prints `map[123:[456]]`
I guess it's convenient compared to Rust's strict approach with entry API. But also, what I found is that golang's subscript returns nil in one case: if the value type is a nested map.
output:
You can test for existence:
https://go.dev/blog/maps#working-with-maps
It returns the zero value for all types, including arrays (which is nil).
nil is equivalent to the empty array, which is why the rest of the code works as it does.
> Also, you can do `value := myMap[someKey]`, and it will just return a value or nil.
It might if your map is a `map[typeA]*typeB` but it definitely won't return a `nil` if your map is anything like `map[typeA]typeC` (where `typeC` is non-nillable; i.e. int, float, string, bool, rune, byte, time.Time, etc.) - you'll get a compile error: "mismatched types typeC and untyped nil".
_ is idiomatic and not an awkward trick. It keeps signatures consistent even when you don't need the value.
> But it's not easier at all, and learning curve just moves to another place.
Hard disagree. Go has its sharp corners, but they don’t even approach the complexity of the borrow checker of Rust alone, let alone all of the other complexity of the Rust ecosystem.