Trait method with returning type of closure

This works well:

fn get(data: usize) -> impl Fn(usize) -> bool {
    move |i: usize| {
        data > i
    }
}

But this not because of rfcs/1522-conservative-impl-trait.md at master · rust-lang/rfcs · GitHub

trait Cond {
    fn get(&self, data: usize) -> impl Fn(usize) -> bool {
        move |i: usize| {
            data > i
        }
    }
}

[E0562] Error: `impl Trait` only allowed in function and inherent method return types, not in trait method return
   ╭─[command_118:1:1]
   │
 2 │     fn get(&self, data: usize) -> impl Fn(usize) -> bool {
   ·                                   ───────────┬──────────  
   ·                                              ╰──────────── error: `impl Trait` only allowed in function and inherent method return types, not in trait method return
───╯

So, is there a inderect way by which I can realize the function of the trait Cond?

I find a way to do it

trait Cond {
    fn get(&self, data: usize) -> Box<dyn Fn(usize) -> bool> {
        Box::new(
            move |i: usize| {
                data > i
            }
        )
    }
}

That's indeed the probably best approach/workaround for now. Allowing impl Trait in this position is likely going to become a thing eventually, too, but at the moment Rust does not support it.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.