Skip to content
Permalink
Browse files
fdas
  • Loading branch information
stnbu committed Nov 12, 2018
1 parent a678c18 commit 5b3c97456c4e8aee1194eea055d4da7fa9f545de
Showing with 11 additions and 52 deletions.
  1. +11 −52 src/main.rs
@@ -21,62 +21,21 @@ fn bytes_to_utf8() {
assert_eq!("💖", sparkle_heart);
}


struct Cacher<T> where T: Fn(u32) -> u32 {
calculation: T,
value: Option<u32>,
}
impl<T> Cacher<T> where T: Fn(u32) -> u32 {
fn new(calculation: T) -> Cacher<T> {
Cacher {
calculation,
value: None,
}
}
fn value(&mut self, arg: u32) -> u32 {
match self.value {
Some(v) => v,
None => {
let v = (self.calculation)(arg);
self.value = Some(v);
v
},
}
}
}
use std::thread;
use std::time::Duration;
fn generate_workout(intensity: u32, random_number: u32) {
let mut expensive_result = Cacher::new(|num| {
println!("calculating slowly...");
thread::sleep(Duration::from_secs(2));
num
});
if intensity < 25 {
println!(
"Today, do {} pushups!",
expensive_result.value(intensity)
);
println!(
"Next, do {} situps!",
expensive_result.value(intensity)
);
} else {
if random_number == 3 {
println!("Take a break today! Remember to stay hydrated!");
} else {
println!(
"Today, run for {} minutes!",
expensive_result.value(intensity)
);
}
}
use std::collections::HashMap;
fn hmap() {
let mut book_reviews = HashMap::new();
book_reviews.insert(3, "foo");
let key = 3;
let x = match book_reviews.get(&key) {
Some(value) => value,
None => "",
};
assert_eq!(x, "foo");
}
//////////

fn main() {
get_element_n_of_string();
misreuse_of_closure();
bytes_to_utf8();
generate_workout(4, 7);
hmap();
}

0 comments on commit 5b3c974

Please sign in to comment.