In Rust, what does declaring `trait Loud: Notifier` require of an implementing type, and which methods can `Loud`'s default bodies call?
answer
- a bound on Self
- two separate impl blocks
- E0277 when the supertrait is missing
- not inheritance of bodies
basics
~20 strait Loud: Notifier means Self: Notifier: a type may implement Loud only if it also implements Notifier in its own impl block. Loud's default bodies, and any code bounded by Loud, can call Notifier's methods on self.
solid answer
~40 s`trait Loud: Notifier` declares `Notifier` as a **supertrait**: it is a bound on `Self`, equivalent to `trait Loud where Self: Notifier`. Implementing `Loud` does not implement `Notifier`; the type needs a separate `impl Notifier for T`, and without it `impl Loud for T {}` fails with E0277, `the trait bound `T: Notifier` is not satisfied`. In return, `Loud`'s default methods may call `self.send(..)`, and any generic or `dyn` value bounded by `Loud` gets `Notifier`'s methods too. It is not class inheritance: a `Loud` impl cannot define or override `send` (E0407), there is no shared state, and each trait's methods still live in that trait's own impl.
code
rust · 31 linesmod notify {
pub trait Notifier {
fn send(&self, msg: &str) -> String;
}
pub trait Loud: Notifier {
fn shout(&self, msg: &str) -> String {
self.send(&msg.to_uppercase())
}
}
pub struct SmsNotifier;
impl Notifier for SmsNotifier {
fn send(&self, msg: &str) -> String {
format!("sms: {msg}")
}
}
impl Loud for SmsNotifier {}
}
use notify::Loud; // Notifier is not imported here
fn alert(n: &impl Loud) -> String {
format!("{} / {}", n.send("disk at 91%"), n.shout("disk full"))
}
fn main() {
println!("{}", alert(¬ify::SmsNotifier));
}go deeper
Recall that trait Loud: Notifier means every Loud type must also implement Notifier, in a separate impl block.
Explain the supertrait as a bound on Self: E0277 without the supertrait impl, E0407 when you put its methods in the subtrait impl, and supertrait methods callable from defaults and bounds.
Show the scope subtlety, that bounds bring supertrait methods along while concrete calls still need the import, and argue when a supertrait is warranted instead of a default method.
Treat each supertrait as a permanent requirement on every implementor and on dyn compatibility, so add them deliberately in public traits rather than for code reuse.
## What a supertrait is Sometimes a trait only makes sense for types that already have some other capability. A `Loud` notifier, which shouts urgent alerts, is built on top of ordinary sending: ```rust trait Notifier { fn send(&self, msg: &str) -> String; } trait Loud: Notifier { fn shout(&self, msg: &str) -> String { self.send(&msg.to_uppercase()) } } ``` The `: Notifier` after the trait name makes `Notifier` a **supertrait** of `Loud`, and `Loud` a **subtrait** of `Notifier`. The Rust Reference defines supertraits as traits that are required to be implemented for a type to implement a specific trait, declared as trait bounds on the `Self` type. So `trait Loud: Notifier` means exactly the same as `trait Loud where Self: Notifier`. Several supertraits combine with `+`, as in `trait Loud: Notifier + Send`. ## What it requires of an implementing type A supertrait is a **requirement, not a gift**. Implementing `Loud` does not implement `Notifier` for you: 1. The type must have its own `impl Notifier for SmsNotifier { fn send(..) {..} }`. 2. It may then write `impl Loud for SmsNotifier {}`, overriding `shout` or not. 3. If step 1 is missing, rustc 1.99.1 rejects step 2 with E0277, `the trait bound `PagerNotifier: Notifier` is not satisfied`, noting that the bound is `required by this bound in `Loud``. The two impl blocks are independent. In particular, the `Loud` impl may contain only `Loud`'s own items: putting `fn send` inside `impl Loud for SmsNotifier` fails with E0407, `method `send` is not a member of trait `Loud``. That is the clearest sign that this is not class inheritance. ## What it gives you Because every `Loud` type is guaranteed to be a `Notifier`, the compiler lets code that knows "this is `Loud`" use `Notifier`'s items: - **Inside `Loud`'s default methods**: `shout` can call `self.send(..)`, as above. - **In generic code**: `fn alert(n: &impl Loud)` or `fn alert<T: Loud>(n: &T)` can call both `n.shout(..)` and `n.send(..)`. The Reference states that anywhere a generic or trait object is bounded by a trait, it has access to the associated items of its supertraits. - **Behind `dyn Loud`**: a `&dyn Loud` can call `send` too; how that interacts with vtables and upcasting belongs with trait objects. A subtle point about scope, checked with rustc 1.99.1: inside `alert(n: &impl Loud)`, `n.send(..)` resolves even if the module imports only `Loud`, because method lookup on a type parameter starts from its bounds. On a **concrete** value, `SmsNotifier.send(..)` in that same module fails with E0599 until `Notifier` itself is imported. Importing a subtrait does not import its supertraits. ## Supertrait versus class inheritance | Question | Supertrait (`trait Loud: Notifier`) | Class inheritance | |---|---|---| | Does implementing the sub-thing provide the parent? | no, write both impls | yes, the subclass is the parent type | | Can the sub-thing override the parent's methods? | no, E0407 | yes | | Is there shared state? | no, traits have no fields | usually | | What the sub-thing gains | permission to call the parent's methods | the parent's fields and bodies | ## Marker traits with supertraits A trait may have no methods at all and still matter. The standard library declares `Copy` as `pub trait Copy: Clone` with an empty body: a **marker trait** that states a property (the value can be duplicated bit for bit) and, through its supertrait, guarantees `Clone` is available as well. Your own code can do the same, for example `trait Audited: Notifier {}` implemented only for notifier types that a security review has approved, then required as a bound wherever approval matters. ## Walking through the snippet The snippet below keeps both traits and `SmsNotifier` inside a module `notify`, and imports only `Loud` at the crate root: 1. `impl Notifier for SmsNotifier` supplies `send`; `impl Loud for SmsNotifier {}` accepts the default `shout`. 2. `alert(n: &impl Loud)` calls `n.send(..)` and `n.shout(..)`. Both resolve, because the `Loud` bound carries `Notifier`'s methods with it. 3. The default `shout` upper-cases the message and calls `self.send`, which is `SmsNotifier`'s own `send`, so the output is `sms: disk at 91% / sms: DISK FULL`. Deleting the `impl Notifier` block produces the E0277 shown in the second example, pointing at the `: Notifier` bound in `Loud`'s declaration. ## Common mistakes - Expecting `impl Loud for T` to make `T` a `Notifier`. - Moving `send` into the `Loud` impl to "override" it. - Importing only `Loud` and then calling `send` on a concrete type. - Adding a supertrait purely to reuse code, when a default method or a free function bounded by `Notifier` would avoid forcing every `Loud` type to carry the extra requirement.
- Is `trait Loud: Notifier` different from `trait Loud where Self: Notifier`?No. The Reference defines supertraits as bounds on `Self`, so both forms declare `Notifier` as a supertrait with the same effect: implementors must also implement `Notifier`, and `Loud`-bounded code can call `Notifier` methods. The colon form is the usual style; the `where` form reads better when the bound list is long.
- Why does `n.send(..)` compile inside `fn alert(n: &impl Loud)` when the module imports only `Loud`?Method lookup on a type parameter checks the methods from its trait bounds first, and supertrait items come along with the `Loud` bound. On a concrete type, the same call needs `Notifier` itself in scope, because lookup there only sees imported traits; importing a subtrait does not import its supertraits.
- What is a marker trait, and how does `Copy` combine one with a supertrait?A marker trait has no methods; implementing it states a property that bounds can require. The standard library declares `Copy` as `pub trait Copy: Clone` with an empty body, but any `Copy` type must also implement `Clone`, so generic code bounded by `Copy` can still call `.clone()`.
- Implementing Loud automatically implements Notifier for the type.
- A Loud impl block can override Notifier's send method.
- A supertrait lets Loud's default methods read Notifier's fields.
- Importing Loud also imports Notifier for calls on concrete types.
- Supertraits mean the subtrait inherits the parent's implementation bodies.