Anon object satisfying trait

Given a trait T

is it possible construct an anonymous object satisfying T, or are we expected to:

  1. define a new struct/type S
  2. do "impl T for S"
  3. return instance of S

The second, explicit one.

1 Like

There's been proposals to allow impl Trait for expressions, sort of as a generalization of closures to other traits beyond the Fn* traits.

pub fn returns_an_anonymous_type_that_impls_debug() -> impl fmt::Debug {
    let this_variable_gets_captured = 123u32;
    let ret = move impl fmt::Debug {
        fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
            write!(fmt, "captured value == {}", this_variable_gets_captured)
        }
    };
    
    ret
}

I don't think there's an RFC for this yet though.

2 Likes