Given a trait T
is it possible construct an anonymous object satisfying T, or are we expected to:
- define a new struct/type S
- do "impl T for S"
- return instance of S
Given a trait T
is it possible construct an anonymous object satisfying T, or are we expected to:
The second, explicit one.
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.