]> piware.de Git - learn-rust.git/blobdiff - src/main.rs
Closures and Cacher object
[learn-rust.git] / src / main.rs
index a4e4f1dafd8aad0114dad8d6612f04fe0d7abbfa..0ef1b16f4f9b19c7e9e1c71377abd4273acc0d1b 100644 (file)
@@ -1,9 +1,11 @@
 mod word_utils;
+mod lib;
 
 use std::collections::HashMap;
 use std::io::{prelude::*, ErrorKind};
 use std::fs::{self, File};
 
+use lib::*;
 use word_utils::{first_word, second_word};
 
 fn test_strings() {
@@ -69,13 +71,6 @@ 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();
@@ -116,47 +111,6 @@ fn test_files() {
     }
 }
 
-// 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));
@@ -183,10 +137,31 @@ fn test_generics() {
     println!("longest string: {}", l);
 }
 
+fn test_closures() {
+    let mut expensive_int_result = Cacher::new(|x| {
+        println!("calculating expensive int result for {}", x);
+        2 * x
+    });
+
+    println!("1st int call for value 1: {}", expensive_int_result.value(1));
+    println!("2nd int call for value 1: {}", expensive_int_result.value(1));
+    println!("1st int call for value 2: {}", expensive_int_result.value(2));
+
+    let mut expensive_str_result = Cacher::new(|x: &str| {
+        println!("calculating expensive str result for {}", x);
+        x.len()
+    });
+
+    println!("1st int call for value abc: {}", expensive_str_result.value("abc"));
+    println!("2nd int call for value abc: {}", expensive_str_result.value("abc"));
+    println!("1st int call for value defg: {}", expensive_str_result.value("defg"));
+}
+
 fn main() {
     test_strings();
     test_vectors();
     test_hashmaps();
     test_files();
     test_generics();
+    test_closures();
 }