You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Unlike closures, fn is a type rather than a trait. Therefore, fn is used directly as the parameter type rather than declaring a generic type parameter with one of the Fn (closure) traits as the trait bound.
Function pointers implement all three of the closure traits (Fn, FnMut, and FnOnce), which means fn can always be passed as an argument for a function that expects a closure. An example of such a function is:
let list = vec![1,2,3];// covert elements to string using closurelet list_strings = list.iter().map(|i| i.to_string()).collect();// using function pointers insteadlet list_strings = list.iter().map(ToString::to_string).collect();
This can be a useful mechanism for generating enum variants. Recall that [[Defining an Enum|enum variants are themselves initializer functions]].
Since closures are represented by traits, they cannot be returned directly.
We have already seen one technique for [[Closures|returning closures]]. This is recalled in the code snippet below. Depending on the functionality implemented by the closure the trait can be Fn, FnMut, or FnOnce.
fnreturn_closure() -> implFn(i32) -> i32{// can be FnMut or FnOnce
|x| x + 1}
In situations where Rust is unable to understand how much size is required to store the closure, a [[Smart Pointers#Box Pointer Using Box<T> to Point to Data on the Heap|box pointer]] with a dyn keyword (similar to [[Trait Objects]]) is necessary.
fnreturns_closure() -> Box<dynFn(i32) -> i32>{Box::new(|x| x + 1)}