]> piware.de Git - learn-rust.git/blob - src/main.rs
Split into functions
[learn-rust.git] / src / main.rs
1 mod word_utils;
2
3 use std::collections::HashMap;
4
5 use word_utils::{first_word, second_word};
6
7 fn test_strings() {
8     let s = String::from("Hello world");
9     println!("first word: '{}'", first_word(&s));
10     println!("second word: '{}'", second_word(&s).unwrap());
11
12     let s2 = "hello dude blah";
13     println!("second word of single: '{}'", second_word(s2).unwrap_or("(none)"));
14
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),
18     }
19 }
20
21 fn test_vectors() {
22     let v1 = vec![1, 2, 3];
23     println!("statically initialized vector: {:?}", v1);
24
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]);
30     for el in &mut v2 {
31         *el += "xx";
32     }
33     for el in &v2 {
34         println!("{}", el);
35     }
36 }
37
38 fn test_hashmaps() {
39     let mut scores = HashMap::new();
40     scores.insert("john", 10);
41     scores.insert("mary", 20);
42
43     println!("scores: {:?}", scores);
44
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);
49
50     for (p, s) in &collect_scores {
51         println!("person {}: score {}", p, s);
52     }
53
54     println!("john's score: {}", scores.get("john").unwrap());
55     println!("jake's score: {}", scores.get("jake").unwrap_or(&-1));
56
57     // double scores
58     for (_, v) in scores.iter_mut() {
59         *v *= 2;
60     }
61     println!("scores after doubling: {:?}", scores);
62
63     // double scores of immutable hashmap (rebuild it)
64     let collect_scores: HashMap<_, _> = collect_scores.iter()
65         .map(|(k, v)| (k, 2 * v))
66         .collect();
67     println!("collect_scores after rebuilding with doubling: {:?}", collect_scores);
68 }
69
70 fn main() {
71     test_strings();
72     test_vectors();
73     test_hashmaps();
74 }