impl Trait

Similar to trait bounds, an impl Trait syntax can be used in function arguments and return values:

  1. use std::fmt::Display;
  2. fn get_x(name: impl Display) -> impl Display {
  3. format!("Hello {name}")
  4. }
  5. fn main() {
  6. let x = get_x("foo");
  7. println!("{x}");
  8. }
  • impl Trait cannot be used with the ::<> turbo fish syntax.
  • impl Trait allows you to work with types which you cannot name.

The meaning of impl Trait is a bit different in the different positions.

  • For a parameter, impl Trait is like an anonymous generic parameter with a trait bound.
  • For a return type, it means that the return type is some concrete type that implements the trait, without naming the type. This can be useful when you don’t want to expose the concrete type in a public API.

This example is great, because it uses impl Display twice. It helps to explain that nothing here enforces that it is the same impl Display type. If we used a single T: Display, it would enforce the constraint that input T and return T type are the same type. It would not work for this particular function, as the type we expect as input is likely not what format! returns. If we wanted to do the same via : Display syntax, we’d need two independent generic parameters.