Start learning free

LESSON 133 OF 679 · DICTIONARIES

Checking for a Key in Rust

Lesson

TL ; DR:

Call map.contains_key(key) to ask whether a HashMap has a key. It returns true or false, so it goes in an if.


let capitals = HashMap::from([("France", "Paris"), ("Japan", "Tokyo")]);

if capitals.contains_key("Japan") {
    println!("{}", capitals["Japan"]);   // Tokyo
}

if !capitals.contains_key("Spain") {
    println!("No Spain");                // No Spain
}


Full lesson:

Reading a missing key with [] panics. capitals["Spain"] stops the program.

So check first. capitals.contains_key("Spain") is true when "Spain" is a key. It is false when it isn't.

Put ! in front for the opposite. !capitals.contains_key("Spain") is true here.

A value is not a key

contains_key looks only at the keys. capitals.contains_key("Paris") is false, because "Paris" is a value.

When the key is a String in a variable, pass a reference, as in contains_key(&name).

A key must match exactly, upper and lower case too. capitals.contains_key("japan") is false.


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 ! and contains_key. 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