From 20dd593509db111575a370a156d716a0bc851312 Mon Sep 17 00:00:00 2001 From: Jordan Gong Date: Sun, 6 Sep 2020 19:15:42 +0800 Subject: Using anonymous functions(closures) --- closures/.gitignore | 18 ++++++++++++++++ closures/Cargo.toml | 9 ++++++++ closures/src/main.rs | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 86 insertions(+) create mode 100644 closures/.gitignore create mode 100644 closures/Cargo.toml create mode 100644 closures/src/main.rs (limited to 'closures') diff --git a/closures/.gitignore b/closures/.gitignore new file mode 100644 index 0000000..e629269 --- /dev/null +++ b/closures/.gitignore @@ -0,0 +1,18 @@ + +# Created by https://www.toptal.com/developers/gitignore/api/rust +# Edit at https://www.toptal.com/developers/gitignore?templates=rust + +### Rust ### +# Generated by Cargo +# will have compiled files and executables +/target/ + +# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries +# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html +Cargo.lock + +# These are backup files generated by rustfmt +**/*.rs.bk + +# End of https://www.toptal.com/developers/gitignore/api/rust + diff --git a/closures/Cargo.toml b/closures/Cargo.toml new file mode 100644 index 0000000..209f8c2 --- /dev/null +++ b/closures/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "closures" +version = "0.1.0" +authors = ["Jordan Gong "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] 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 +where + T: Fn(u32) -> u32, +{ + calculation: T, + value: Option, +} + +impl Cacher +where + T: Fn(u32) -> u32, +{ + fn new(calculation: T) -> Cacher { + 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); +} -- cgit v1.2.3