|
|
|
|
|
by rob74
1864 days ago
|
|
Err... Go does exactly what "most languages" do too! You can write: value, _ := map[key]
and if map[key] doesn't exist, value will be set to the "zero value" of the map's type. So Go doesn't force you to handle the error. The actual reason for the "verbosity" is just that you can't simply write if(map[key]) { ...
because map[key] returns two values (and "if" wants to have a boolean expression). But if you really have to do this so often that it's bothering you, you should question yourself why... |
|
The actual reason you cannot simply write:
aside from the extraneous parens, is because Go syntax does not permit implicit default values/truthiness in its 'if' statements like that (as you say "if wants to have a boolean expression"). That's the real reason for the verbosity here.But you certainly can write:
if the map contained strings, or: if it contained booleans, etc. (For what that may be worth: checking for default value isn't the same as checking membership in all instances, of course).Because map[key] can in fact return one — or two — values, depending on its usage context.