WeCodeAcademy

Rust Vectors and HashMaps

ExampleRust
use std::collections::HashMap;

fn main() {
    let mut v = vec![5, 2, 9];
    v.push(1);
    v.sort();
    println!("{:?} len {}", v, v.len());
    let doubled: Vec<i32> = v.iter().map(|n| n * 2).collect();
    println!("{:?}", doubled);
    let total: i32 = v.iter().sum();
    println!("{}", total);

    let mut ages = HashMap::new();
    ages.insert("Ada", 36);
    ages.insert("Sam", 22);
    println!("{:?}", ages.get("Ada"));
    println!("{:?}", ages.get("Nobody"));
    println!("{}", ages.len());
}
Output
[1, 2, 5, 9] len 4
[2, 4, 10, 18]
17
Some(36)
None
2

get returns an Option: either Some(value) or None. Rust has no null: the possibility of a missing value is part of the type.

Quick check

What does HashMap::get return?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.