hash map rust code example

Example: rust hashmap

use std::collections::HashMap;

fn main() {

    // create
    let mut sample: HashMap<String, i32> = HashMap::new();

    // insert data
    sample.insert("one".to_string(), 1);
    sample.insert("two".to_string(), 2);
    sample.insert("three".to_string(), 3);
    sample.insert("four".to_string(), 4);

    // print contents
    for (key, value) in sample.iter() {
        println!("{} - {}", key, value);
    }
    
    // insert with uniqueness check first
    if sample.contains_key("five") {
        println!("five: {:?}", sample.get("five"));
    } else {
        sample.insert("five".to_string(), 5);
    }

    // remove element
    sample.remove("four");

    println!("");
    for (key, value) in sample.iter() {
        println!("{} - {}", key, value);
    }
}

Tags:

Rust Example