Search code examples
rusttraits

What does the trait after the trait name mean?


I came across this trait definition while reading about Rust:

trait Enchanter: std::fmt::Debug {
    ...
}

From this I understand that the name of the trait is Enchanter, but I do not understand what the std::Format:Debug part implies since it is also a trait (I think).


Solution

  • This is declaring a supertrait. It is equivalent to:

    trait Enchanter
    where
        Self: std::fmt::Debug,
    {
    }
    

    In short, it requires any type that wants to implement Enchanter to also implement std::fmt::Debug. Otherwise, an error will be raised:

    error[E0277]: `S` doesn't implement `Debug`
     --> src/lib.rs:4:6
      |
    4 | impl Enchanter for S {}
      |      ^^^^^^^^^ `S` cannot be formatted using `{:?}`
      |
      = help: the trait `Debug` is not implemented for `S`
      = note: add `#[derive(Debug)]` to `S` or manually `impl Debug for S`
    note: required by a bound in `Enchanter`
     --> src/lib.rs:1:18
      |
    1 | trait Enchanter: std::fmt::Debug {}
      |                  ^^^^^^^^^^^^^^^ required by this bound in `Enchanter`