use std::collections::HashMap; fn get_default(v: &Vec, i: usize, default_value: &u32) -> u32 { match v.get(i) { Some(value) => *value, None => *default_value, } } fn get_default_2(v: &Vec, i: usize, default_value: &u32) -> u32 { *v.get(i).unwrap_or(default_value) } fn vec_example() { let mut v = Vec::new(); v.push(2); v.push(5); println!("v[0] = {:?}", v.get(6)); // OK, returns an Option println!("v[0] = {}", v[6]); // stops the program } fn map_example() { let mut map = HashMap::new(); map.insert(1, String::from("1")); let key = &1; // checks that the key is in the map // but hashes the key twice: // - to check if it is in the map // - to get the value from the map if map.contains_key(key) { // sure that it exists let val = map.get(key).expect("something weird happened here"); // example of unsafe code // avoid writing unsafe code for now // (very easy to shoot yourself in the foot...) // let val = unsafe { // // it is up to you to be extra carefull here // map.get(key).unwrap_unchecked() // }; } // usefull API here: the `entry` method of map let uppercase = map.entry(2).or_insert(String::from("2")).to_uppercase(); }