-
-
Save se1983/dc876e2fc477031f0535d1d6682a5596 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::thread; | |
use std::time::Duration; | |
use std::collections::HashMap; | |
struct Cacher<T> where T: Fn(u32) -> u32{ | |
calculation: T, | |
values: HashMap<u32, u32> | |
} | |
impl<T> Cacher<T> where T: Fn(u32) -> u32 { | |
fn new(calculation: T) -> Cacher<T> { | |
Cacher{ | |
calculation, values: HashMap::new() | |
} | |
} | |
fn values(&mut self, arg: u32) -> u32 { | |
match self.values.get(&arg){ | |
Some(x) => *x, | |
None => { | |
let x = (self.calculation)(arg); | |
self.values.insert( | |
arg, x | |
); | |
x | |
} | |
} | |
} | |
} | |
fn generate_workout(intensity: u32, random_number: u32){ | |
let mut expensive_result = Cacher::new(|num| { | |
println!("calculation slowly ..."); | |
thread::sleep(Duration::from_secs(3)); | |
num | |
}); | |
if intensity < 25{ | |
println!("Today {} pushups", expensive_result.values(intensity)); | |
println!("Next do {} situps", expensive_result.values(intensity)); | |
} else { | |
if random_number == 3{ | |
println!("Take a break today!"); | |
} else { | |
println!("Today run for {} minutes", expensive_result.values(intensity)); | |
} | |
} | |
} | |
fn main() { | |
let simulated_user_specific_value = 10; | |
let simulated_random_number = 7; | |
generate_workout( | |
11, | |
simulated_random_number | |
); | |
generate_workout( | |
10, | |
simulated_random_number | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment