Start learning free

LESSON 129 OF 671 · DICTIONARIES

Checking for a Key in Go

Lesson

TL ; DR:

The comma-ok lookup tells you whether a map has a key. Its ok is true when the key is there, so it goes in an if.


capitals := map[string]string{"France": "Paris", "Japan": "Tokyo"}

if _, ok := capitals["Japan"]; ok {
    fmt.Println(capitals["Japan"])   // Tokyo
}

if _, ok := capitals["Spain"]; !ok {
    fmt.Println("No Spain")          // No Spain
}


Full lesson:

You met this lookup in Maps & the ok Idiom. A missing key gives the zero value, here "". And ok is false.

Only ok tells a missing key from a key that holds "". So don't check with capitals["Spain"] == "".

The _ throws the value away. This check needs only ok.

The lookup can sit in the if line, before a ;. Then ok exists only inside that if.

!ok asks the opposite. It is true when the key is missing.

A value is not a key

A lookup looks only at the keys. capitals["Paris"] gives an ok of false, because "Paris" is a value.

A key must match exactly, upper and lower case too. capitals["japan"] misses as well.


Your task

In pets, each key is a pet's name, and its value is the pet's kind.

First, check whether "Tom" is a key of pets. If it is, print Tom is a followed by Tom's kind.

Then check that "cat" is not a key, with a comma-ok lookup and !ok. If so, print cat is not a key.

"cat" is in pets, but only as a value. It is Tom's kind.

Expected output:

Tom is a cat
cat is not a key
STEP 1 OF 2
    Ctrl + Enter to check