]> piware.de Git - learn-rust.git/blob - src/main.rs
ff65a0611a6e7b40a0a86501a239ab657cc4156a
[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 main() {
8     // strings and functions
9     let s = String::from("Hello world");
10     println!("first word: '{}'", first_word(&s));
11     println!("second word: '{}'", second_word(&s).unwrap());
12
13     let s2 = "hello dude blah";
14     println!("second word of single: '{}'", second_word(s2).unwrap_or("(none)"));
15
16     match second_word(s2) {
17         Some(w) => println!("match: second word of '{}' exists: {}", s2, w),
18         None => println!("match: second word of '{}' does not exist", s2),
19     }
20
21     // 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     // hash maps
38     let mut scores = HashMap::new();
39     scores.insert("john", 10);
40     scores.insert("mary", 20);
41
42     println!("scores: {:?}", scores);
43
44     // hash map with .collect()
45     let persons = vec![("homer", 42), ("marge", 30)];
46     let collect_scores: HashMap<_, _> = persons.into_iter().collect();
47     println!("collect_scores: {:?}", collect_scores);
48
49     for (p, s) in &collect_scores {
50         println!("person {}: score {}", p, s);
51     }
52
53     println!("john's score: {}", scores.get("john").unwrap());
54     println!("jake's score: {}", scores.get("jake").unwrap_or(&-1));
55
56     // double scores
57     for (_, v) in scores.iter_mut() {
58         *v *= 2;
59     }
60     println!("scores after doubling: {:?}", scores);
61
62     // double scores of immutable hashmap (rebuild it)
63     let collect_scores: HashMap<_, _> = collect_scores.iter()
64         .map(|(k, v)| (k, 2 * v))
65         .collect();
66     println!("collect_scores after rebuilding with doubling: {:?}", collect_scores);
67 }