error[E0562]: `impl Trait` is not allowed in closure parameters

Hello.

As far as I can see, it is not possible to create a closure with a impl Trait argument:

fn main() {
    // Works.
    fn x(iter: impl Iterator<Item = char>) {
        for c in iter {
            println!("c: {}", c);
        }
    }

    // error[E0562]: `impl Trait` is not allowed in closure parameters
    let y = |iter: impl Iterator<Item = char>| {
        for c in iter {
            println!("c: {}", c);
        }
    };
}

Is it actually not possible, or maybe other syntax is needed? Is it just not implemented yet, or there is a reason why it can't be implemented?

I assume it is that. There is the impl-trait-initiative that is supposed to bring impl Trait syntax to more places like let bindings or type declarations[1]. They recently brought us RPITITs (return-position impl Trait in trait), so I think it's fair to say that impl Trait syntax is still very much in development.


  1. Couldn't find type declarations in closures being actively tracked somewhere though. ↩ī¸Ž

2 Likes

Note that there are two meanings for impl Trait:

  • in a function argument positions it's a shortcut for a generic parameter with a trait object; this is what OP showed, but since closures can't be generic it results in a compile error;
  • in a function return position it's a way to make the return type opaque, and more importantly allows to avoid naming it; this is what the initiative is (was? the repository hasn't recevied a useful commit in ~2 years) about, because it turns out there are a bunch of types that we can't name but would be very useful to be able to refer to them in more places.
3 Likes