golang

Learn How to check if key exists in Map in Golang


In this article, you will learn about how to check if a key exists in a map in the Go language.

Go language provides a built-in associative data type named Map which is basically a collection of key-value pairs. On the map, you can retrieve, delete or update values with the help of keys. As we know that a map in the Go language consists of key-value pairs. You can easily find out whether a Map consists of a key or not. But first thing first, lets see an example of a Map in Go language.

package main

import "fmt"

func main() {
        var student = map[string]int{
                "Deven":   23,
        }
        for name, age := range student {
                fmt.Println("Name:", name, "=>", "Age:", age)
        }
    }

/*
    Output:
    Name: Deven => Age: 23
*/

Now, let’s check, if this example exists a key or not. To do so, we will simply run if-else condition. See the example below:

package main

import "fmt"

func main() {
        var student = map[string]int{
                "Deven": 23,
        }
        value, ok := student["Deven"]
        if ok {
                fmt.Println("Key found value is: ", value)
        } else {
                fmt.Println("Key not found")
        }
    }

/*
    Output: Key is found and value is:  23
*/

Here, we can see that the key is found in the map which is Deven and the value for it is 23. Now lets try if there is no value in the map.

package main

import "fmt"

func main() {
        var student = map[string]int{
                "Deven": 23,
        }
        value, ok := student["Alex"]
        if ok {
                fmt.Println("Key is found and value is: ", value)
        } else {
                fmt.Println("Key is not found")
        }
    }

/*
    Output: Key is not found
*/

Here, in the map, there is no key exists named “Alex”. So it simply shows the output as “key is not found” and by following this approach you can check if a key exists in a map in the Go language.


Share on social media

//