Closures
Closures are anonymous functions that capture the scope in which they are defined. They can be saved as a variable or passed into a function.
rust
struct HelloWorld {
msg: String
}
impl HelloWorld {
fn test_closure(&self, name: Option<&str>) -> String {
String::from(format!(self.msg, name.unwrap_or_else(|| self.default_name())))
}
fn default_name() -> String {
return String::from("David")
}
}
// Example with parameter and return value
let expensive_closure = |num: u32| -> u32 {
println!("calculating slowly...");
thread::sleep(Duration::from_secs(2));
num
};
Ownership and References
Immutable reference
rust
let list = vec![1, 2, 3];
println!("Before defining closure: {:?}", list);
let only_borrows = || println!("From closure: {:?}", list);
println!("Before calling closure: {:?}", list);
only_borrows();
println!("After calling closure: {:?}", list);
Mutable reference
rust
let mut list = vec![1, 2, 3];
println!("Before defining closure: {:?}", list);
let mut borrows_mutably = || list.push(7);
borrows_mutably();
println!("After calling closure: {:?}", list);
Take ownership with move
rust
use std::thread;
let list = vec![1, 2, 3];
println!("Before defining closure: {:?}", list);
thread::spawn(move || println!("From thread: {:?}", list))
.join()
.unwrap();