This question already has an answer here:
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)
</div>
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
}
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
}