# Advanced Functions and Closures ## Function Pointers We can pass Closures (Static Functions) into Functions as Parameters. We can also pass functions! `fn` is really jsut a type identifier! ```rust fn do_twice(f: fn(i32)->i32, arg:i32) -> i32 { f(arg) + f(arg)} ``` `fn` =/= `Fn` which is from the Closure Types (`Fn` `FnMut` `FnOnce`). A Function Pointer is compatible with all Closure Types, so you can pass a Functor in any that expects a Closure. To avoid it, is recommended to write functions with a Generic of the Closure Trait. Uses: interfacing with external code that only accepts functions ("C"). Ex: Instead of passing a Closure to the collection functions, pass another function that will then be executed on the iteration! ```rust let list_of_numbers = vec![1, 2, 3]; // Valid closure that makes use of method form th value let list_of_strings: Vec = list_of_numbers.iter().map(|i| i.to_string()).collect(); // Instead, we just pass the method that iter will have inevitably let list_of_strings: Vec = list_of_numbers.iter().map(ToString::to_string).collect(); ``` Use the style that feels appropiate to the use and user. ## Returning Closures ```rust fn return_closure() -> dyn Fn(i32) -> i32 { |x| x+1 } // illegal, we don't know size of the type of dyn ... // Use trait object! fn return_closure() -> Box i32> { |x| x+1 } ```