Hacker News new | ask | show | jobs
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...
2 comments

You can actually write:

  value := map[key]
and if map[key] doesn't exist, value will (still) be set to the "zero value" of the map's type.

The actual reason you cannot simply write:

  if(map[key]) { ...
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 map[key] != "" { ...
if the map contained strings, or:

  if map[key] { ...
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.

Go forces you to handle the error, which you agree with because you handled it by explicitly ignoring it via _.