Hacker News new | ask | show | jobs
by jimsmart 1864 days ago
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.