Can I pass a function as a parameter? If not, what is a good alternative?
I tried some different syntaxes but I have not found the right one. I know I can do this:>
Fn, FnMut and FnOnce, outlined in the other answer, are closure types. The types of functions that close over their scope.
Apart from passing closures Rust also supports passing simple (non-closure) functions, like this:
fn times2(value: i32) -> i32 {
2 * value
}
fn fun_test(value: i32, f: fn(i32) -> i32) -> i32 {
println!("{}", f (value));
value
}
fn main() {
fun_test (2, times2);
}
fn(i32) -> i32 here is a function pointer type.
If you don't need a full-fledged closure than working with function types is often simpler as it doesn't have to deal with those closure lifetime nicities.