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 example() {
let fun: fn(value: i32) -> i32;
fun = fun_test;
fun(5i32);
}
fn fun_test(value: i32) -> i32 {
println!("{}", value);
value
}
but that's not passing the function as a parameter to another function:
fn fun_test(value: i32, (some_function_prototype)) -> i32 {
println!("{}", value);
value
}
Sure you can:
As this is Rust, you have to take into account the ownership and lifetime of the closure.
TL;DR; Basically there are 3 types of closures (callable objects):
Fn
: It cannot modify the objects it captures.FnMut
: It can modify the objects it captures.FnOnce
: The most restricted. Can only be called once because when it is called it consumes itself and its captures.See When does a closure implement Fn, FnMut and FnOnce? for more details
If you are using a simple pointer-to-function like closure, then the capture set is empty and you have the
Fn
flavor.If you want to do more fancy stuff, then you will have to use lambda functions.
In Rust there are proper pointers to functions, that work just like those in C. Their type is for example
fn(i32) -> i32
. TheFn(i32) -> i32
,FnMut(i32) -> i32
andFnOnce(i32) -> i32
are actually traits. A pointer to a function always implements all three of these, but Rust also has closures, that may or may not be converted to pointers (depending on whether the capture set is empty) to functions but they do implement some of these traits.So for example, the example from above can be expanded:
Fn
,FnMut
andFnOnce
, 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(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.