What is the correct syntax to return a function in Rust?
The following code does not compile.
fn identity<T>(a: T) -> T {
return a;
};
fn right<T>(a: T) -> Fn {
return identity;
};
Here (playground) is a minimal example:
fn identity<T>(a: T) -> T {
return a;
}
fn right<T>(_a: T) -> impl Fn(T) -> T {
return identity;
}
fn main() {
println!("{}", right(0)(42))
}
You need to:
Fn(T) -> T
.right
's return type impl
ements the trait Fn(T) -> T
.Alternatively, you could also have written the function pointer fn(T) -> T
as the return type. Since this is not a trait, you would not need the impl
keyword:
fn right<T>(_a: T) -> fn(T) -> T {
return identity;
}
Only fn
items and non-capturing closures can be coerced to function pointers, so, while simpler, this will not work in all cases.