How to Check if a Key Exists in a Map in Go

The clearest, simplest way to check whether a key exists in a map is as follows:

value, found := mymap[key]

if !found {
    // key not found 🙁 return error
}

// key found, do something with value

Now, you might say

“There are too many lines! I want more succinctness!”

Don’t worry, there are other ways that I will quickly run through. My preference is the method above, other people will have other preferences.

So, if you don’t need to do anything with the value, but want to make sure it exists before proceeding, then that is alright, you can just ignore the value with an underscore:

if _, found := mymap[key]; !found {
    return fmt.Errorf("key not found :(")
}

fmt.Println("key exists! now what?")

Succinct, clear. Good.

But what if you want to use the value? Well, you can do this:

if value, found := mymap[key]; found {
    // do something with the value, since it exists!
    // note lack of ! in if condition
}

// can't access value here, or found variable.

There are a few things I don’t like here. I feel like the error condition should be in the if block, like an if err != nil {...}, but it isn’t. I also don’t like not being able to access the value after the if block. So the alternative is this:

var value string // Type must match map obviously

if value, found := mymap[key]; !found {
    return fmt.Errorf("key not found :(")
}

fmt.Println("Key found:", value)

Note that you need to have value in the code before the if statement, this will allow you to access it after the if block. Sometimes you’ll have already done this, in which case you save 1 line of code doing it this way! But in many cases you won’t actually save any, and have slightly harder to read code.

Leave a Reply

Your email address will not be published. Required fields are marked *