]> piware.de Git - learn-rust.git/blobdiff - src/main.rs
Split into functions
[learn-rust.git] / src / main.rs
index 7a83cb487326028805912df69daa38a3c2cfa394..e61306ac95077cf475e0b60fd11d573531a09e2d 100644 (file)
@@ -1,28 +1,10 @@
-mod word_utils {
-    pub fn first_word(s: &str) -> &str {
-        for (i, &item) in s.as_bytes().iter().enumerate() {
-            if item == b' ' {
-                return &s[..i];
-            }
-        }
-
-        s
-    }
-
-    pub fn second_word(s: &str) -> Option<&str> {
-        for (i, &item) in s.as_bytes().iter().enumerate() {
-            if item == b' ' {
-                return Some(first_word(&s[(i + 1)..]));
-            }
-        }
+mod word_utils;
 
-        return None;
-    }
-}
+use std::collections::HashMap;
 
 use word_utils::{first_word, second_word};
 
-fn main() {
+fn test_strings() {
     let s = String::from("Hello world");
     println!("first word: '{}'", first_word(&s));
     println!("second word: '{}'", second_word(&s).unwrap());
@@ -35,3 +17,58 @@ fn main() {
         None => println!("match: second word of '{}' does not exist", s2),
     }
 }
+
+fn test_vectors() {
+    let v1 = vec![1, 2, 3];
+    println!("statically initialized vector: {:?}", v1);
+
+    let mut v2: Vec<String> = Vec::new();
+    v2.push("Hello".to_string());
+    v2.push(String::from("world"));
+    println!("dynamically built vector: {:?}", v2);
+    println!("first element: {}", v2[0]);
+    for el in &mut v2 {
+        *el += "xx";
+    }
+    for el in &v2 {
+        println!("{}", el);
+    }
+}
+
+fn test_hashmaps() {
+    let mut scores = HashMap::new();
+    scores.insert("john", 10);
+    scores.insert("mary", 20);
+
+    println!("scores: {:?}", scores);
+
+    // hash map with .collect()
+    let persons = vec![("homer", 42), ("marge", 30)];
+    let collect_scores: HashMap<_, _> = persons.into_iter().collect();
+    println!("collect_scores: {:?}", collect_scores);
+
+    for (p, s) in &collect_scores {
+        println!("person {}: score {}", p, s);
+    }
+
+    println!("john's score: {}", scores.get("john").unwrap());
+    println!("jake's score: {}", scores.get("jake").unwrap_or(&-1));
+
+    // double scores
+    for (_, v) in scores.iter_mut() {
+        *v *= 2;
+    }
+    println!("scores after doubling: {:?}", scores);
+
+    // double scores of immutable hashmap (rebuild it)
+    let collect_scores: HashMap<_, _> = collect_scores.iter()
+        .map(|(k, v)| (k, 2 * v))
+        .collect();
+    println!("collect_scores after rebuilding with doubling: {:?}", collect_scores);
+}
+
+fn main() {
+    test_strings();
+    test_vectors();
+    test_hashmaps();
+}