Rust Traits Placing a bound on a trait


When defining a new trait it is possible to enforce that types wishing to implement this trait verify a number of constraints or bounds.

Taking an example from the standard library, the DerefMut trait requires that a type first implement its sibling Deref trait:

pub trait DerefMut: Deref {
    fn deref_mut(&mut self) -> &mut Self::Target;

This, in turn, enables DerefMut to use the associated type Target defined by Deref.

While the syntax might be reminiscent of inheritance:

  • it brings in all the associated items (constants, types, functions, ...) of the bound trait
  • it enables polymorphism from &DerefMut to &Deref

This is different in nature:

  • it is possible to use a lifetime (such as 'static) as a bound
  • it is not possible to override the bound trait items (not even the functions)

Thus it is best to think of it as a separate concept.