|
| 1 | +// closures2.rs |
| 2 | +// |
| 3 | +// How do closures capture their state? Well, the answer is "it depends on how you use it!" |
| 4 | +// |
| 5 | +// Usage inside the closure body will tell the compiler how the value should be captured. |
| 6 | +// |
| 7 | +// Capture by shared reference? Mutable reference? Ownership? Let's try and see! |
| 8 | +// |
| 9 | +// Execute `rustlings hint closures2` or use the `hint` watch subcommand for a hint. |
| 10 | + |
| 11 | +fn main() { |
| 12 | + // Using a non-Copy type because it makes reasoning about capturing easier |
| 13 | + let s = String::from("Hello, rustlings!"); |
| 14 | + let capture_by_ref = || { |
| 15 | + println!("{s}"); // This only requires a &String, so it only captures a &String |
| 16 | + }; |
| 17 | + // You can continue to use s as a &String outside the closure, but not &mut String or String. |
| 18 | + println!("Outside capture_by_ref closure: {s}"); |
| 19 | + capture_by_ref(); |
| 20 | + |
| 21 | + // Notice the mut here |
| 22 | + // v |
| 23 | + let mut s = String::from("Hello, rustlings!"); |
| 24 | + let mut capture_by_mut = || { |
| 25 | + s.truncate(5); // Requires &mut String: also can be written as String::truncate(&mut s, 5); |
| 26 | + println!("{s}"); // This should print nothing (and a line break) |
| 27 | + // Since the "most" we need is mutable, it captures a single mutable reference to String. |
| 28 | + }; |
| 29 | + capture_by_mut(); |
| 30 | + |
| 31 | + let mut s = String::from("Hello, rustlings!"); |
| 32 | + let capture_by_ownership = || { |
| 33 | + s.truncate(5); // Requires &mut String |
| 34 | + println!("{s}"); // This should print nothing (and a line break) |
| 35 | + let boxed = s.into_boxed_str(); // Requires ownership: String::into_boxed_str(s); |
| 36 | + println!("{boxed}"); // This should print nothing (and a line break) |
| 37 | + }; |
| 38 | + capture_by_ownership(); |
| 39 | + |
| 40 | + let s = String::from("Hello, rustlings!"); |
| 41 | + let quiz = || { |
| 42 | + let captured_s = &s; // Using a shared reference fixes the issue. |
| 43 | + println!("Inside Closure quiz {captured_s}"); |
| 44 | + }; |
| 45 | + println!("Outside Closure quiz {s}"); |
| 46 | + quiz(); |
| 47 | +} |
0 commit comments