Check if key exists in a map in Go

0
2
Check if key exists in a map in Go
Check if key exists in a map in Go

In this post, I will show you a tip to check if key exists in a map in Go (golang).

When we access the value from a key in a map, it returns two values:

value, ok := mapName[key]

If the key is set or exists, ok will return true; otherwise, it will return false.

Let’s take at following sample code snippet:

package main

import "fmt"

func main() {
	mapArticle := make(map[string]string)

	mapArticle["author"] = "Pete Houston"

	author, ok := mapArticle["author"]
	fmt.Printf("Author: %s | ok: %t\n", author, ok)

	title, ok := mapArticle["title"]
	fmt.Printf("Title: %s | ok: %t\n", title, ok)
}

This is the output when executing the code:

Author: Pete Houston | ok: true
Title:  | ok: false

As expected, if the key exists, ok is true and false when key doesn’t exist.

Therefore, we can improve by making the conditional check before accessing the value, something like this:

title, ok := mapArticle["title"]
if ok {
	fmt.Printf("Title: %s | ok: %t\n", title, ok)
} else {
	fmt.Printf("Key 'title' doesn't exist")
}

That’s how you check if key exists in a map in Go.

Have fun!