]> piware.de Git - learn-rust.git/blob - src/main.rs
Return style fix
[learn-rust.git] / src / main.rs
1 mod word_utils;
2
3 use std::collections::HashMap;
4 use std::io::{prelude::*, ErrorKind};
5 use std::fs::{self, File};
6
7 use word_utils::{first_word, second_word};
8
9 fn test_strings() {
10     let s = String::from("Hello world");
11     println!("first word: '{}'", first_word(&s));
12     println!("second word: '{}'", second_word(&s).unwrap());
13
14     let s2 = "hello dude blah";
15     println!("second word of single: '{}'", second_word(s2).unwrap_or("(none)"));
16
17     match second_word(s2) {
18         Some(w) => println!("match: second word of '{}' exists: {}", s2, w),
19         None => println!("match: second word of '{}' does not exist", s2),
20     }
21 }
22
23 fn test_vectors() {
24     let v1 = vec![1, 2, 3];
25     println!("statically initialized vector: {:?}", v1);
26
27     let mut v2: Vec<String> = Vec::new();
28     v2.push("Hello".to_string());
29     v2.push(String::from("world"));
30     println!("dynamically built vector: {:?}", v2);
31     println!("first element: {}", v2[0]);
32     for el in &mut v2 {
33         *el += "xx";
34     }
35     for el in &v2 {
36         println!("{}", el);
37     }
38 }
39
40 fn test_hashmaps() {
41     let mut scores = HashMap::new();
42     scores.insert("john", 10);
43     scores.insert("mary", 20);
44
45     println!("scores: {:?}", scores);
46
47     // hash map with .collect()
48     let persons = vec![("homer", 42), ("marge", 30)];
49     let collect_scores: HashMap<_, _> = persons.into_iter().collect();
50     println!("collect_scores: {:?}", collect_scores);
51
52     for (p, s) in &collect_scores {
53         println!("person {}: score {}", p, s);
54     }
55
56     println!("john's score: {}", scores.get("john").unwrap());
57     println!("jake's score: {}", scores.get("jake").unwrap_or(&-1));
58
59     // double scores
60     for (_, v) in scores.iter_mut() {
61         *v *= 2;
62     }
63     println!("scores after doubling: {:?}", scores);
64
65     // double scores of immutable hashmap (rebuild it)
66     let collect_scores: HashMap<_, _> = collect_scores.iter()
67         .map(|(k, v)| (k, 2 * v))
68         .collect();
69     println!("collect_scores after rebuilding with doubling: {:?}", collect_scores);
70 }
71
72 fn read_file(path: &str) -> Result<String, std::io::Error> {
73     let mut s = String::new();
74     File::open(path)?
75         .read_to_string(&mut s)?;
76     Ok(s)
77 }
78
79 fn test_files() {
80     if let Ok(mut f) = File::open("Cargo.toml") {
81         let mut contents = String::new();
82         match f.read_to_string(&mut contents) {
83             Ok(len) => println!("successfully opened Cargo.toml: {:?}, contents {} bytes:\n{}\n----------", f, len, contents),
84             Err(e) => panic!("could not read file: {:?}", e)
85         }
86     } else {
87         println!("could not open Cargo.toml");
88     }
89
90     // alternative form, more specific error checking
91     let mut f = File::open("Cargo.toml").unwrap_or_else(|e| {
92         if e.kind() == ErrorKind::NotFound {
93             println!("Cargo.toml not found, falling back to /dev/null");
94             // need to return a File
95             File::open("/dev/null").unwrap()
96         } else {
97             panic!("Could not open Cargo.toml: {:?}", e);
98         }
99     });
100     let mut contents = String::new();
101     let len = f.read_to_string(&mut contents).unwrap_or_else(|e| {
102         panic!("Could not read file: {:?}", e);
103     });
104     println!("successfully opened Cargo.toml with unwrap_or_else: {:?}, contents {} bytes:\n{}\n----------", f, len, contents);
105
106     // using the '?' operator
107     match read_file("Cargo.toml") {
108         Ok(s) => println!("Cargo.toml contents:\n{}\n-------------", s),
109         Err(e) => println!("Could not open Cargo.toml: {:?}", e)
110     }
111
112     // using std API
113     match fs::read_to_string("Cargo.toml") {
114         Ok(s) => println!("Cargo.toml contents:\n{}\n-------------", s),
115         Err(e) => println!("Could not open Cargo.toml: {:?}", e)
116     }
117 }
118
119 fn main() {
120     test_strings();
121     test_vectors();
122     test_hashmaps();
123     test_files();
124 }