-
Notifications
You must be signed in to change notification settings - Fork 0
/
closures_with_fn_trait_obj.rs
57 lines (50 loc) · 1.34 KB
/
closures_with_fn_trait_obj.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
use std::thread;
use std::time::Duration;
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, args: u32) -> u32 {
match self.value {
Some(v) => v,
None => {
let val = (self.calculation)(args);
self.value = Some(val);
val
}
}
}
}
fn generate_workout(intensity: u32, random_number: u32) {
let mut expensive_result = Cacher::new(|num| {
println!("[!!] Calculating very slow..");
thread::sleep(Duration::from_secs(2));
num
});
if intensity < 25 {
println!("Do {} pushups",expensive_result.value(intensity));
println!("Do {} situps",expensive_result.value(intensity));
}else {
if random_number == 3 {
println!("[+] Take rest today, remember to stay hydrated!!");
}else {
println!("[+] Do the running for {} minutes",expensive_result.value(intensity));
}
}
}
fn main() {
let simulated_high_number = 22;
let simulated_random_number = 4;
generate_workout(simulated_high_number, simulated_random_number)
}