From 59bc706d0a024a4b19ee9f57ac33e9c5463e7ffd Mon Sep 17 00:00:00 2001 From: Timothy Warren Date: Mon, 11 Feb 2019 09:34:46 -0500 Subject: [PATCH] Add advanced_functions example --- .idea/misc.xml | 1 + .idea/rust.iml | 5 ++ .idea/workspace.xml | 96 +++++++++++++++++++--------------- advanced_functions/Cargo.toml | 7 +++ advanced_functions/src/main.rs | 38 ++++++++++++++ 5 files changed, 105 insertions(+), 42 deletions(-) create mode 100644 advanced_functions/Cargo.toml create mode 100644 advanced_functions/src/main.rs diff --git a/.idea/misc.xml b/.idea/misc.xml index 06e172b..197e36a 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -40,6 +40,7 @@ + diff --git a/.idea/rust.iml b/.idea/rust.iml index 54d35f8..6566c66 100644 --- a/.idea/rust.iml +++ b/.idea/rust.iml @@ -161,9 +161,14 @@ + + + + + diff --git a/.idea/workspace.xml b/.idea/workspace.xml index 5708fa1..3212679 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -15,10 +15,18 @@ - + - - + + + + + + + + + + @@ -52,7 +60,6 @@ @@ -112,7 +120,7 @@ false false - + - + @@ -203,7 +211,7 @@ - + + + - - + - @@ -325,8 +333,8 @@ - - + + @@ -334,7 +342,7 @@ - + @@ -356,17 +364,6 @@ - - - - - - - - - - - @@ -563,13 +560,6 @@ - - - - - - - @@ -804,7 +794,29 @@ - + + + + + + + + + + + + + + + + + + + + + + + diff --git a/advanced_functions/Cargo.toml b/advanced_functions/Cargo.toml new file mode 100644 index 0000000..c0e5634 --- /dev/null +++ b/advanced_functions/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "advanced_functions" +version = "0.1.0" +authors = ["Timothy Warren "] +edition = "2018" + +[dependencies] diff --git a/advanced_functions/src/main.rs b/advanced_functions/src/main.rs new file mode 100644 index 0000000..d128ff2 --- /dev/null +++ b/advanced_functions/src/main.rs @@ -0,0 +1,38 @@ +fn add_one(x: i32) -> i32 { + x + 1 +} + +/// A function with a function pointer argument +fn do_twice(f: fn(i32) -> i32, arg: i32) -> i32 { + f(arg) + f(arg) +} + +#[derive(Debug)] +enum Status { + Value(u32), + Stop, +} + +fn returns_closure() -> Box i32> { + Box::new(|x| x + 1) +} + +fn main() { + let answer = do_twice(add_one, 5); + + println!("The answer is: {}", answer); + + // Tuple Structs set up via function pointers + let list_of_statuses: Vec = + (0u32..20) + .map(Status::Value) + .collect(); + + println!("List of statuses: {:?}", list_of_statuses); + + let increment = returns_closure(); + let x = 5; + let y = increment(x); + + println!("The returned closure returns: {}", y); +}