fntest_vector() { println!("Test the usage of vector!"); // create a new vector letnew_vec_test: Vec<i32> = Vec::new(); println!("{new_vec_test:?}"); // or we can just use macro letnew_vec_test = vec![1, 2, 3]; println!("{new_vec_test:?}");
// pushing elements for mutable vectors letmut v: Vec<i32> = Vec::new(); v.push(22); v.push(224); foriin1..=100 { v.push(i * i); }
println!("{v:?}");
// reading elements from vectors // using borrowing // method1: using [] slices letfirst_value: &i32 = &v[0]; println!("{}", first_value);
// method2: using .get method, returning None if index out of bound letfirst_value: Option<&i32> = v.get(2); match first_value { Some(third) => { println!("{}", third); } None => println!("None"), }
// ! after getting the reference, we cannot modify the vector in case of data race
// traverse elements in vector foriin &v { // borrowing println!("{i}"); }
// advanced usage for (index, value) in v.iter().enumerate() { println!("Index: {index} with value: {value}"); }
// or modifying them in a mut vector! letmut v = vec![100, 32, 57]; foriin &mut v { println!("{i}"); // ! attention, while modifying the value with a mutable reference, * (dereference operation) is required. *i += 50; println!("{i}"); } }
// concat string lets1 = String::from("hello"); lets2 = String::from(" world"); lets3 = s1 + &s2; // ! now s1 can not be used // function: fn add(self, s: &str) -> String // String can be transformed into &str, with Deref Coercion println!("{}",s3);
// or using format macro lets4 = String::from("Hello!"); letconcat_s = format!("{s3}-{s2}-{s4}"); println!("{concat_s}"); }
fntest_hashmap() { letmut scores: HashMap<String, i32> = HashMap::new(); // the ownership will be removed in the inserting process scores.insert(String::from("Hello world"), 33); scores.insert(String::from("Lili"), 150); scores.insert(String::from("What the fuck"), 300); letteam_name = String::from("Hello world"); letscore = scores.get(&team_name).copied().unwrap_or(0); // .get function: pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V> // for the get function, it will return Option<&i32> // unwrap_or(): handle None println!("{}", score);
// support traversing for (key, value) in &scores { println!("{key}: {value}"); }
// advanced API: entry // if value exists, don't do anything, else insert with the value use_entry(); use_if_else(); use_if_let(); demo(); }