3 use std::collections::HashMap;
5 use word_utils::{first_word, second_word};
8 let s = String::from("Hello world");
9 println!("first word: '{}'", first_word(&s));
10 println!("second word: '{}'", second_word(&s).unwrap());
12 let s2 = "hello dude blah";
13 println!("second word of single: '{}'", second_word(s2).unwrap_or("(none)"));
15 match second_word(s2) {
16 Some(w) => println!("match: second word of '{}' exists: {}", s2, w),
17 None => println!("match: second word of '{}' does not exist", s2),
22 let v1 = vec![1, 2, 3];
23 println!("statically initialized vector: {:?}", v1);
25 let mut v2: Vec<String> = Vec::new();
26 v2.push("Hello".to_string());
27 v2.push(String::from("world"));
28 println!("dynamically built vector: {:?}", v2);
29 println!("first element: {}", v2[0]);
39 let mut scores = HashMap::new();
40 scores.insert("john", 10);
41 scores.insert("mary", 20);
43 println!("scores: {:?}", scores);
45 // hash map with .collect()
46 let persons = vec![("homer", 42), ("marge", 30)];
47 let collect_scores: HashMap<_, _> = persons.into_iter().collect();
48 println!("collect_scores: {:?}", collect_scores);
50 for (p, s) in &collect_scores {
51 println!("person {}: score {}", p, s);
54 println!("john's score: {}", scores.get("john").unwrap());
55 println!("jake's score: {}", scores.get("jake").unwrap_or(&-1));
58 for (_, v) in scores.iter_mut() {
61 println!("scores after doubling: {:?}", scores);
63 // double scores of immutable hashmap (rebuild it)
64 let collect_scores: HashMap<_, _> = collect_scores.iter()
65 .map(|(k, v)| (k, 2 * v))
67 println!("collect_scores after rebuilding with doubling: {:?}", collect_scores);