In this section, we're going to see how to check whether a key exists in a given map. So we have a map, nameAges
, which basically maps names to ages. Check out the following code:
package main import "fmt" func main() { nameAges := map[string]int{ "Tarik": 32, "Michael": 30, "Jon": 25, } fmt.Println(nameAges["Tarik"]) }
As you can see from the following screenshot, we basically fetched the value from the Tarik
key. Therefore, it returned only one value, which was 32
:
However, there's another way of using this map that returns two things: the first is the value and the second is whether the key exists. For instance, check out the following code:
package main import "fmt" func main() { nameAges := map[string]int{ "Tarik": 32, "Michael": 30, "Jon": 25, } value, exists := nameAges["Tarik"] fmt.Println(value) fmt.Println(exists) }
The output will be as follows:
As you can see, the code returns true
because Tarik
,...