From 087355502db044f8cb72cc6870da6a3c916c6064 Mon Sep 17 00:00:00 2001 From: Dan Buch Date: Thu, 19 Oct 2023 11:08:38 -0400 Subject: [PATCH] A few more RBE things --- rustbyexample/fn.d/closures.d/anonymity.rs | 14 ++++++++ .../fn.d/closures.d/input_parameters.rs | 36 +++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 rustbyexample/fn.d/closures.d/anonymity.rs create mode 100644 rustbyexample/fn.d/closures.d/input_parameters.rs diff --git a/rustbyexample/fn.d/closures.d/anonymity.rs b/rustbyexample/fn.d/closures.d/anonymity.rs new file mode 100644 index 0000000..64d8f53 --- /dev/null +++ b/rustbyexample/fn.d/closures.d/anonymity.rs @@ -0,0 +1,14 @@ +fn apply(f: F) +where + F: Fn(), +{ + f(); +} + +fn main() { + let x = 7; + + let print = || println!("{}", x); + + apply(print); +} diff --git a/rustbyexample/fn.d/closures.d/input_parameters.rs b/rustbyexample/fn.d/closures.d/input_parameters.rs new file mode 100644 index 0000000..01fcec1 --- /dev/null +++ b/rustbyexample/fn.d/closures.d/input_parameters.rs @@ -0,0 +1,36 @@ +fn apply(f: F) +where + F: FnOnce(), +{ + f(); +} + +fn apply_to_3(f: F) -> i32 +where + F: Fn(i32) -> i32, +{ + f(3) +} + +fn main() { + use std::mem; + + let greeting = "hello"; + let mut farewell = "goodbye".to_owned(); + + let diary = || { + println!("I said {}.", greeting); + + farewell.push_str("!!!"); + println!("Then I screamed {}.", farewell); + println!("Now I can sleep. zzzzz"); + + mem::drop(farewell); + }; + + apply(diary); + + let double = |x| 2 * x; + + println!("3 doubled: {}", apply_to_3(double)); +}