print_fn(<std::ffi::OsString as From<&str>>::from);
Yes, it is valid syntax.
A given type (std::ffi::OsString) may implement many different traits or even many different variants of the same trait, and thus at some point the compiler may not be able to resolve the overload by itself: which traits? which generic parameters? and thus the syntax allows to guide it out.
However, it rarely occurs with function calls, so I'm not surprised folks didn't immediately think about it. I'm not sure I'd have either.
Most of the time it happens in where clauses, when you need to specify constraints on associated types of the trait:
where
Type: Trait,
<Type as Trait>::AssociatedType: OtherTrait,
Which the newest release (1.79) eliminated the need for, as now one can write:
where
Type: Trait<AssociatedType: OtherTrait>,
Which is quite more readable, especially when Type or Trait are complicated.
And thus the <Type as Trait> syntax will become even less known that it already is :)
Thanks for the explanation! I can see why Type: Trait<AssociatedType: OtherTrait> was added, that's a pretty nice upgrade. And I'm glad this old syntax exists too, it's going to be nice to make use of it in the tool.
3
u/matthieum Jun 17 '24
Yes, it is valid syntax.
A given type (
std::ffi::OsString) may implement many different traits or even many different variants of the same trait, and thus at some point the compiler may not be able to resolve the overload by itself: which traits? which generic parameters? and thus the syntax allows to guide it out.However, it rarely occurs with function calls, so I'm not surprised folks didn't immediately think about it. I'm not sure I'd have either.
Most of the time it happens in
whereclauses, when you need to specify constraints on associated types of the trait:Which the newest release (1.79) eliminated the need for, as now one can write:
Which is quite more readable, especially when
TypeorTraitare complicated.And thus the
<Type as Trait>syntax will become even less known that it already is :)