]> piware.de Git - learn-rust.git/blobdiff - src/main.rs
Generics and Traits
[learn-rust.git] / src / main.rs
index 973bb2e6c8a3ff790ed25a03f690ea48c6a29084..a4e4f1dafd8aad0114dad8d6612f04fe0d7abbfa 100644 (file)
@@ -2,7 +2,7 @@ mod word_utils;
 
 use std::collections::HashMap;
 use std::io::{prelude::*, ErrorKind};
-use std::fs::File;
+use std::fs::{self, File};
 
 use word_utils::{first_word, second_word};
 
@@ -69,6 +69,13 @@ fn test_hashmaps() {
     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();
@@ -95,6 +102,85 @@ fn test_files() {
         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)
+    }
+}
+
+// needs Copy trait, good for simple types
+fn largest<T: PartialOrd + Copy>(list: &[T]) -> T {
+    let mut result = list[0];
+    for &i in list {
+        if i > result {
+            result = i;
+        }
+    }
+    result
+}
+
+// expensive for large strings, don't use that
+fn largest_clone<T: PartialOrd + Clone>(list: &[T]) -> T {
+    let mut result = list[0].clone();
+    for i in list {
+        if *i > result {
+            result = i.clone();
+        }
+    }
+    result
+}
+
+// good for everything, but more expensive for simple types
+fn largest_ref<T: PartialOrd>(list: &[T]) -> &T {
+    let mut result = &list[0];
+    for i in list {
+        if i > result {
+            result = i;
+        }
+    }
+    result
+}
+
+fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
+    if x.len() > y.len() {
+        x
+    } else {
+        y
+    }
+}
+
+fn test_generics() {
+    let num_list = vec![3, 42, -7, 100, 0];
+    println!("largest number: {}", largest(&num_list));
+    println!("num_list: {:?}", num_list);
+
+    let char_list = vec!['a', 'y', 'q', 'm'];
+    println!("largest char: {}", largest(&char_list));
+
+    let str_list = vec!["hello", "world", "blue", "planet"];
+    println!("largest str: {}", largest(&str_list));
+    println!("str_list: {:?}", str_list);
+
+    let string_list = vec!["aaaa".to_string(), "xxxxx".to_string(), "ffff".to_string()];
+    println!("largest string (with cloning): {}", largest_clone(&string_list));
+    println!("largest string (with ref): {}", largest_ref(&string_list));
+    println!("string_list: {:?}", string_list);
+
+    let s1 = String::from("abcd");
+    let l;
+    {
+        let s2 = "efghi";
+        l = longest(&s1, s2);
+    }
+    println!("longest string: {}", l);
 }
 
 fn main() {
@@ -102,4 +188,5 @@ fn main() {
     test_vectors();
     test_hashmaps();
     test_files();
+    test_generics();
 }