Anon object satisfying trait


#1

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

#2

The second, explicit one.


#3

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.