[Q] On returning a closure


In the RPL book (paper version) page 448 there is an example of returning a closure.

I experimented a bit and found a second working version using impl instead of Box.

fn main() {
    fn return_closure() -> Box<dyn Fn(i32) -> i32> {
        let y = 3;
        Box::new(move |x| x + y)
    let dck = return_closure();
    println!("Return van de closure {}", dck(3));

    fn return_closure2() -> impl Fn(i32) -> i32 {
        let y = 3;
        move |x| x + y
    let dck2 = return_closure2();
    println!("Return van de closure {}", dck2(3));

Is there a difference?
Which implementation is preferred?


With former approach you need heap allocation and dynamic dispatch which is generally slower, but you can get the actual type name. With latter approach you returns plain struct and static dispatch but you can’t get the actual type name (yet). Also, every Box<dyn Trait> are same type but every impl Trait are different type so they can’t be used exchangeably.

General answer is: prefer to use impl Trait, until you can’t compile with it.