]> piware.de Git - learn-rust.git/blobdiff - src/main.rs
Return style fix
[learn-rust.git] / src / main.rs
index ff65a0611a6e7b40a0a86501a239ab657cc4156a..c07c4051165861365a2176a3c1edec6957d16903 100644 (file)
@@ -1,11 +1,12 @@
 mod word_utils;
 
 use std::collections::HashMap;
+use std::io::{prelude::*, ErrorKind};
+use std::fs::{self, File};
 
 use word_utils::{first_word, second_word};
 
-fn main() {
-    // strings and functions
+fn test_strings() {
     let s = String::from("Hello world");
     println!("first word: '{}'", first_word(&s));
     println!("second word: '{}'", second_word(&s).unwrap());
@@ -17,8 +18,9 @@ fn main() {
         Some(w) => println!("match: second word of '{}' exists: {}", s2, w),
         None => println!("match: second word of '{}' does not exist", s2),
     }
+}
 
-    // vectors
+fn test_vectors() {
     let v1 = vec![1, 2, 3];
     println!("statically initialized vector: {:?}", v1);
 
@@ -33,8 +35,9 @@ fn main() {
     for el in &v2 {
         println!("{}", el);
     }
+}
 
-    // hash maps
+fn test_hashmaps() {
     let mut scores = HashMap::new();
     scores.insert("john", 10);
     scores.insert("mary", 20);
@@ -65,3 +68,57 @@ fn main() {
         .collect();
     println!("collect_scores after rebuilding with doubling: {:?}", collect_scores);
 }
+
+fn read_file(path: &str) -> Result<String, std::io::Error> {
+    let mut s = String::new();
+    File::open(path)?
+        .read_to_string(&mut s)?;
+    Ok(s)
+}
+
+fn test_files() {
+    if let Ok(mut f) = File::open("Cargo.toml") {
+        let mut contents = String::new();
+        match f.read_to_string(&mut contents) {
+            Ok(len) => println!("successfully opened Cargo.toml: {:?}, contents {} bytes:\n{}\n----------", f, len, contents),
+            Err(e) => panic!("could not read file: {:?}", e)
+        }
+    } else {
+        println!("could not open Cargo.toml");
+    }
+
+    // alternative form, more specific error checking
+    let mut f = File::open("Cargo.toml").unwrap_or_else(|e| {
+        if e.kind() == ErrorKind::NotFound {
+            println!("Cargo.toml not found, falling back to /dev/null");
+            // need to return a File
+            File::open("/dev/null").unwrap()
+        } else {
+            panic!("Could not open Cargo.toml: {:?}", e);
+        }
+    });
+    let mut contents = String::new();
+    let len = f.read_to_string(&mut contents).unwrap_or_else(|e| {
+        panic!("Could not read file: {:?}", e);
+    });
+    println!("successfully opened Cargo.toml with unwrap_or_else: {:?}, contents {} bytes:\n{}\n----------", f, len, contents);
+
+    // using the '?' operator
+    match read_file("Cargo.toml") {
+        Ok(s) => println!("Cargo.toml contents:\n{}\n-------------", s),
+        Err(e) => println!("Could not open Cargo.toml: {:?}", e)
+    }
+
+    // using std API
+    match fs::read_to_string("Cargo.toml") {
+        Ok(s) => println!("Cargo.toml contents:\n{}\n-------------", s),
+        Err(e) => println!("Could not open Cargo.toml: {:?}", e)
+    }
+}
+
+fn main() {
+    test_strings();
+    test_vectors();
+    test_hashmaps();
+    test_files();
+}