0

A Tour of Go explains how to test that a key is present in the map:

m := make(map[string]int)
m["Answer"] = 42
v, ok := m["Answer"]
if ok { Do Something if set }
if !ok { Do Something if not set }

Is there a way to test it without the assignment, expression way, something similar to this:

if m["Answer"] IS NOT NULL  { Do Something if set }
if m["Answer"] IS NULL  { Do Something if not set }

Or

fmt.Println(m["Answer"] == nil)
exebook
  • 32,014
  • 33
  • 141
  • 226
  • @Flimzy I need something you can put between `if` and opening `{` – exebook Feb 25 '17 at 17:35
  • **I have voted to reopen.** This is _clearly_ different question. You can see in the question that he is aware of the `value, exists := m["key"]` expression, and this question is **not** asking about it. He is asking about how to examine the presence of a key _without assignment_. Those can’t see it must be illiterate or blind. – Константин Ван Apr 28 '21 at 18:43

2 Answers2

3

I think you're trying not to assign to the v and ok variables?

This is not possible. However, there is a short hand available:

if v, ok := m["Answer"]; ok {
    // Do something with `v` if set
} else {
    // Do something if not set, v will be the nil value
}

If you don't care about the value, but only that it's set, replace v with _.

if _, ok := m["Answer"]; ok {
    // Do something if set
} else {
    // Do something if not set
}
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
2

You can use _ as a placeholder if you don't care to store the value.

eg.

_, ok := m["Answer"]
if !ok {
  // do something
} else {
  // do something else
}

Or, you can condense this a bit:

if _, ok := m["Answer"]; ok {
  // do something
} else {
  // do something else
}
MahlerFive
  • 5,159
  • 5
  • 30
  • 40