To verify if a given key exists in a map in Go, use the particular type of the index expression
v, okay := a[k]
which returns two components – a price v
of the map with the important thing ok
, and a boolean worth okay
equal to true
if the important thing ok
is current within the map. If not, the okay
is fake.
Instance
information := map[string]int{
"a": 1,
"b": 2,
"c": 3,
}
val, okay := information["a"]
fmt.Println(val, okay)
val, okay = information["d"]
fmt.Println(val, okay)
Output:
Methods to verify if a key exists in a map straight in an if assertion
In on a regular basis coding, a standard state of affairs is that you just solely need to execute a sure piece of code if a given key exists within the map. In Go, you are able to do this by combining the if
assertion with the map index expression.
if val, okay := information["a"]; okay {
fmt.Println(val, okay)
}
if val, okay := information["d"]; okay {
fmt.Println(val, okay)
}
Output:
If
statements will be preceded by easy statements that will let you assign map values straight within the if
, earlier than evaluating it.
Why is checking for zero values not adequate?
Chances are you’ll be questioning why we can’t use the easier map index expression which returns a single worth and verify if it’s not the zero worth:
if information["a"] != 0 {
fmt.Println("key a exists")
}
Output:
It really works wonderful in case you are certain that your map doesn’t include zero values. In any other case, the end result will likely be incorrect:
// incorrect end result
information["d"] = 0
if information["d"] != 0 {
fmt.Println("key d exists")
} else {
fmt.Println("key d doesn't exist")
}
Output:
Because of this, it’s a higher concept to make use of a two-values map index expression for checking whether or not a map incorporates a given key in Go.