Introduction
In this lab, we learn that closures can be used as input parameters and can also be returned as output parameters by utilizing impl Trait and specifying the valid traits (Fn, FnMut, FnOnce). The move keyword is used to indicate that all captures occur by value, avoiding invalid references.
Note: If the lab does not specify a file name, you can use any file name you want. For example, you can use
main.rs, compile and run it withrustc main.rs && ./main.
As output parameters
Closures as input parameters are possible, so returning closures as output parameters should also be possible. However, anonymous closure types are, by definition, unknown, so we have to use impl Trait to return them.
The valid traits for returning a closure are:
FnFnMutFnOnce
Beyond this, the move keyword must be used, which signals that all captures occur by value. This is required because any captures by reference would be dropped as soon as the function exited, leaving invalid references in the closure.
fn create_fn() -> impl Fn() {
let text = "Fn".to_owned();
move || println!("This is a: {}", text)
}
fn create_fnmut() -> impl FnMut() {
let text = "FnMut".to_owned();
move || println!("This is a: {}", text)
}
fn create_fnonce() -> impl FnOnce() {
let text = "FnOnce".to_owned();
move || println!("This is a: {}", text)
}
fn main() {
let fn_plain = create_fn();
let mut fn_mut = create_fnmut();
let fn_once = create_fnonce();
fn_plain();
fn_mut();
fn_once();
}
Summary
Congratulations! You have completed the As Output Parameters lab. You can practice more labs in LabEx to improve your skills.