Start learning free

LESSON 117 OF 679 · ARRAYS I

Checking a Vec for a Value in Rust

Lesson

TL ; DR:

v.contains(&x) is true when the Vec holds x, and false when it doesn't. Note the & before the value.


let colors = vec!["red", "green", "blue"];

println!("{}", colors.contains(&"red"));    // true

println!("{}", colors.contains(&"pink"));   // false

if !colors.contains(&"pink") {
    println!("No pink yet");
}


Full lesson:

Often you need to know if a Vec holds some value. Is this name on the guest list? Is this item in the cart?

contains answers that. It compares each item with the value, from the first one on. It returns true as soon as one matches, or false if none does.

It wants a reference to the value, not the value itself. So write & before it, as in colors.contains(&"red"). Without the &, the code doesn't compile.

Put ! in front for the opposite. So !colors.contains(&x) is true when x is missing.

The answer is a bool, so it fits right into an if:

let cart = vec!["milk", "bread"];

if cart.contains(&"milk") {
    println!("Milk is in the cart");
}

Text must match exactly. So colors.contains(&"Red") is false, because the Vec has "red".


Your task

bag holds what is packed for a hike.

If "water" is in bag, print Water is packed. If "tent" is not in bag, print Pack a tent.

Expected output:

Water is packed
Pack a tent
STEP 1 OF 2
    Ctrl + Enter to check