summaryrefslogtreecommitdiff
path: root/closures/src
diff options
context:
space:
mode:
authorJordan Gong <jordan.gong@protonmail.com>2020-09-06 19:15:42 +0800
committerJordan Gong <jordan.gong@protonmail.com>2020-09-06 19:15:42 +0800
commit20dd593509db111575a370a156d716a0bc851312 (patch)
tree953be6b9eeddfe201a726705b5a292893980d9aa /closures/src
parent6d664454222885c8bcf64e7935fcf8da7c3d9a11 (diff)
Using anonymous functions(closures)
Diffstat (limited to 'closures/src')
-rw-r--r--closures/src/main.rs59
1 files changed, 59 insertions, 0 deletions
diff --git a/closures/src/main.rs b/closures/src/main.rs
new file mode 100644
index 0000000..91bd189
--- /dev/null
+++ b/closures/src/main.rs
@@ -0,0 +1,59 @@
+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, arg: u32) -> u32 {
+ match self.value {
+ Some(v) => v,
+ None => {
+ let v = (self.calculation)(arg);
+ self.value = Some(v);
+ v
+ }
+ }
+ }
+}
+
+fn generate_work(intensity: u32, random_number: u32) {
+ let mut expensive_clourse = Cacher::new(|num| {
+ println!("calculating slowly...");
+ thread::sleep(Duration::from_secs(2));
+ num
+ });
+
+ if intensity < 25 {
+ println!("Today, do {} pushups!", expensive_clourse.value(intensity));
+ println!("Next, do {} situps!", expensive_clourse.value(intensity));
+ } else {
+ if random_number == 3 {
+ println!("Take a break today! Remember to stay hydrated!");
+ } else {
+ println!("Today, run for {} minutes!", expensive_clourse.value(intensity));
+ }
+ }
+}
+
+fn main() {
+ let simulated_user_specified_value = 10;
+ let simulated_random_number = 7;
+
+ generate_work(simulated_user_specified_value, simulated_random_number);
+}