2 ms·
You're right. But it will return something: https://go.dev/play/p/Cz6aeGpURgo https://go.dev/play/p/Cz6aeGpURgo my_map := make(map[int32][]int64) val := my
by culebron21 11mo ago
You're right. But it will return something: https://go.dev/play/p/Cz6aeGpURgo https://go.dev/play/p/Cz6aeGpURgo
my_map := make(map[int32][]int64)
val := my_map[123]
val = append(val, 456)
my_map[123] = val
fmt.Println(my_map)
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.
my_map := make(map[int32]map[int32]int64)
val := my_map[123]
val[456] = 789
my_map[123] = val
fmt.Println(my_map)
output:
panic: assignment to entry in nil map
- HL33tibCe7 11mo agoIt 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.
- tiltowait 11mo agoYou can test for existence: val, ok := my_map[123] if ok { ... } https://go.dev/blog/maps#working-with-maps https://go.dev/blog/maps#working-with-maps