Returning a closure from a function
As of Rust 1.26, you can use impl trait
:
fn make_adder(a: i32) -> impl Fn(i32) -> i32 {
move |b| a + b
}
fn main() {
println!("{}", make_adder(1)(2));
}
This allows returning an unboxed closure even though it is impossible to specify the exact type of the closure.
This will not help you if any of these are true:
You are targeting Rust before this version
-
You have any kind of conditional in your function:
fn make_adder(a: i32) -> impl Fn(i32) -> i32 { if a > 0 { move |b| a + b } else { move |b| a - b } }
Here, there isn't a single return type; each closure has a unique, un-namable type.
-
You need to be able to name the returned type for any reason:
struct Example<F>(F); fn make_it() -> Example<impl Fn()> { Example(|| println!("Hello")) } fn main() { let unnamed_type_ok = make_it(); let named_type_bad: /* No valid type here */ = make_it(); }
You cannot (yet) use
impl SomeTrait
as a variable type.
In these cases, you need to use indirection. The common solution is a trait object, as described in the other answer.
It is possible to return closures inside Box
es, that is, as trait objects implementing certain trait:
fn make_adder(a: i32) -> Box<Fn(i32) -> i32> {
Box::new(move |b| a + b)
}
fn main() {
println!("{}", make_adder(1)(2));
}
(try it here)
There is also an RFC (its tracking issue) on adding unboxed abstract return types which would allow returning closures by value, without boxes, but this RFC was postponed. According to discussion in that RFC, it seems that some work is done on it recently, so it is possible that unboxed abstract return types will be available relatively soon.
The ||
syntax is still the old boxed closures, so this doesn't work for the same reason it didn't previously.
And, it won't work even using the correct boxed closure syntax |&:| -> int
, since it is literally is just sugar for certain traits. At the moment, the sugar syntax is |X: args...| -> ret
, where the X
can be &
, &mut
or nothing, corresponding to the Fn
, FnMut
, FnOnce
traits, you can also write Fn<(args...), ret>
etc. for the non-sugared form. The sugar is likely to be changing (possibly something like Fn(args...) -> ret
).
Each unboxed closure has a unique, unnameable type generated internally by the compiler: the only way to talk about unboxed closures is via generics and trait bounds. In particular, writing
fn make_adder(a: int, b: int) -> |&:| -> int {
|&:| a + b
}
is like writing
fn make_adder(a: int, b: int) -> Fn<(), int> {
|&:| a + b
}
i.e. saying that make_adder
returns an unboxed trait value; which doesn't make much sense at the moment. The first thing to try would be
fn make_adder<F: Fn<(), int>>(a: int, b: int) -> F {
|&:| a + b
}
but this is saying that make_adder
is returning any F
that the caller chooses, while we want to say it returns some fixed (but "hidden") type. This required abstract return types, which says, basically, "the return value implements this trait" while still being unboxed and statically resolved. In the language of that (temporarily closed) RFC,
fn make_adder(a: int, b: int) -> impl Fn<(), int> {
|&:| a + b
}
Or with the closure sugar.
(Another minor point: I'm not 100% sure about unboxed closures, but the old closures certainly still capture things by-reference which is another thing that sinks the code as proposed in the issue. This is being rectified in #16610.)