rust_programming_book 0.1.1

Programming works from THE RUST PROGRAMMING LANGUAGE
Documentation
use std::collections::HashMap;

#[allow(dead_code)]
fn basic_operation() {
    let mut scores = HashMap::new();
    scores.insert("green", 10);
    scores.insert("red", 20);
    // later code overrides
    scores.insert("red", 50);

    // copied maps Option<&T> to Option<T>
    let value1 = scores.get("red").copied().unwrap_or(0);
    let value2 = scores.get("red").unwrap_or(&0);

    // result will be same
    println!("{:#?}", value1);
    println!("{:#?}", value2);

    for (key, value) in scores {
        println!("key: {}, value: {}", key, value);
    }
}
#[allow(dead_code)]
fn hashmap_and_ownership() {
    let mut hashmap1 = HashMap::new();
    let mut hashmap2 = HashMap::new();
    let key1 = "np";
    let value1 = "+977";
    hashmap1.insert(key1, value1);
    // first checks whether there is already a key pair
    hashmap1.entry("us").or_insert("+1");

    let key2 = String::from("hello");
    let value2 = String::from("world");
    hashmap2.insert(key2, value2);

    // ownership is not transferred to hashmap for types that implement Copy traits(like, &str, i32 and
    // other scalar data type). But for compound(String, Struct) etc ownership will be moved to hash map
    // unless we insert reference of the key and pair.
    println!("Key1: {}", key1);
    println!("value1: {}", value1);

    // generates error as ownership of key2 and value2 is transferred to hashmap
    // println!("{}", key2);
}

// updating hash map's old value

fn update_hash_map() {
    let text = "hello world wonderful world";

    let mut map = HashMap::new();

    for word in text.split_whitespace() {
        let count = map.entry(word).or_insert(0);
        *count = *count + 1;
    }

    println!("{:#?}", map);
}

#[allow(dead_code)]
pub fn collection() {
    // basic_operation();
    // hashmap_and_ownership();
    update_hash_map();
}