DEV Community

Cover image for How to check if a map contains a key in Go?

How to check if a map contains a key in Go?

courseprobe profile image Course Probe ・2 min read

In this brief tutorial we’ll explore 2 examples to check if a key is in map in golang, this might be useful for those who want to check map in go for the existence of a key.

Example 1:

if val, ok := dict["foo"]; ok {
    //do something here
Enter fullscreen mode Exit fullscreen mode

if statements in Go can include both a condition and an initialization statement. The example above uses both:

  • initializes two variables — val will receive either the value of "foo" from the map or a "zero value" (in this case the empty string) and ok will receive a bool that will be set to true if "foo" was actually present in the map

  • evaluates ok, which will be true if "foo" was in the map

If “foo” is indeed present in the map, the body of the if statement will be executed and val will be local to that scope.

Example 2:

package main

import "fmt"

func main() {
        dict := map[string]int {"foo" : 1, "bar" : 2}
        value, ok := dict["baz"]
        if ok {
                fmt.Println("value: ", value)
        } else {
                fmt.Println("key not found")
Enter fullscreen mode Exit fullscreen mode


Get the book: Learn GO Programming

Other Dev posts you might like:

Discussion (0)

Editor guide