Cookies management by TermsFeed Cookie Consent

🗝️ Check if a map contains a key in Go

introduction map

To check if a given key exists in a map in Go, use the special form of the index expression

v, ok := a[k]
which returns two elements - a value v of the map with the key k, and a boolean value ok equal to true if the key k is present in the map. If not, the ok is false.

Example

data := map[string]int{
    "a": 1,
    "b": 2,
    "c": 3,
}

val, ok := data["a"]
fmt.Println(val, ok)
val, ok = data["d"]
fmt.Println(val, ok)

Output:

1 true
0 false

How to check if a key exists in a map directly in an if statement

In everyday coding, a common situation is that you only want to execute a certain piece of code if a given key exists in the map. In Go, you can do this by combining the if statement with the map index expression.

if val, ok := data["a"]; ok {
    fmt.Println(val, ok)
}
if val, ok := data["d"]; ok {
    fmt.Println(val, ok)
}

Output:

1 true

If statements can be preceded by simple statements that allow you to assign map values directly in the if, before evaluating it.

Why is checking for zero values not sufficient?

You may be wondering why we cannot use the simpler map index expression which returns a single value and check if it is not the zero value:

if data["a"] != 0 {
    fmt.Println("key a exists")
}

Output:

key a exists

It works fine if you are sure that your map does not contain zero values. Otherwise, the result will be incorrect:

// incorrect result
data["d"] = 0
if data["d"] != 0 {
    fmt.Println("key d exists")
} else {
    fmt.Println("key d does not exist")
}

Output:

key d does not exist

For this reason, it is a better idea to use a two-values map index expression for checking whether a map contains a given key in Go.


Thank you for being on our site 😊. If you like our tutorials and examples, please consider supporting us with a cup of coffee and we'll turn it into more great Go examples.

Have a great day!

Buy Me A Coffee

💕 Copy a map in Go

Learn how to copy all elements of a map to another
introduction map

🫘 Count the occurrences of an element in a slice in Go

Learn how to count elements in a slice that meet certain conditions
introduction generics generics-intro

❤️‍🩹 Recover function in Go

Learn what it is for and how to use the built-in recover() function
introduction syntax builtin