|
| 1 | +// closures1.rs |
| 2 | +// |
| 3 | +// "Why do we even need closures?" is a question that gets asked from time to time. |
| 4 | +// While it's true that most things that closures can do can also be done with |
| 5 | +// regular old structs and enums, closures can make things a lot more clear with a lot |
| 6 | +// less clutter compared to structs. |
| 7 | +// |
| 8 | +// Below is a good example of how one could implement a capturing closure using structs, |
| 9 | +// and how closures simplifies this greatly. |
| 10 | +// |
| 11 | +// Execute `rustlings hint closures1` or use the `hint` watch subcommand for a hint. |
| 12 | + |
| 13 | +// I AM NOT DONE |
| 14 | + |
| 15 | + |
| 16 | +trait Doorman { |
| 17 | + fn greet_customer(&self, customer_name: &str); |
| 18 | +} |
| 19 | + |
| 20 | +struct GreeterWithState<'a> { |
| 21 | + greeting: &'a str, |
| 22 | +} |
| 23 | + |
| 24 | +impl Doorman for GreeterWithState<'_> { |
| 25 | + fn greet_customer(&self, customer_name: &str) { |
| 26 | + println!("{}, {}?", self.greeting, customer_name); |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +fn greet_customers(doorman: impl Doorman) { |
| 31 | + doorman.greet_customer("Bill"); |
| 32 | + doorman.greet_customer("Alex"); |
| 33 | + doorman.greet_customer("John"); |
| 34 | + doorman.greet_customer("Jessie"); |
| 35 | +} |
| 36 | + |
| 37 | +fn greet_customers_closure(doorman: impl Fn(&str)) { |
| 38 | + doorman("Bill"); |
| 39 | + doorman("Alex"); |
| 40 | + doorman("John"); |
| 41 | + doorman("Jessie"); |
| 42 | +} |
| 43 | + |
| 44 | +fn main() { |
| 45 | + let greeting = String::from("Hello! How are you"); |
| 46 | + |
| 47 | + // Method 1 for passing in functions with state. |
| 48 | + // Just create a struct, store the state, and add a method. |
| 49 | + // If you need to be generic, it can be a trait method. |
| 50 | + let doorman = GreeterWithState { |
| 51 | + greeting: &greeting, |
| 52 | + }; |
| 53 | + greet_customers(doorman); |
| 54 | + |
| 55 | + // Method 2 for passing in functions with state. |
| 56 | + // Notice that the body of this closure is exactly the same |
| 57 | + // as GreeterWithState's Doorman implementation. |
| 58 | + // |
| 59 | + // This makes things much cleaner with less clutter, but |
| 60 | + // we are forgetting something very important. |
| 61 | + greet_customers_closure(|customer_name| { |
| 62 | + println!("{}, {}?", self.greeting, customer_name); // TODO: Only modify this line |
| 63 | + }) |
| 64 | +} |
0 commit comments