Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Get value from hash

  • get

  • from

  • get returns an Option containing the value corresponding to the key, or None, if the key does not exist.

use std::collections::HashMap;

fn main() {
    let counter = HashMap::from([("foo", 1), ("bar", 2)]);
    println!("{}", counter["foo"]);
    println!("{:?}", counter.get("foo"));

    // println!("{}", counter["zz"]); // panic
    println!("{:?}", counter.get("zz")); // None

    println!();

    match counter.get("foo") {
        Some(val) => println!("{val}"),
        None => println!("None"),
    };

    match counter.get("zz") {
        Some(val) => println!("{val}"),
        None => println!("None"),
    };
}
1
Some(1)
None

1
None