Why does sealed trait require a module?

⚓ Rust    📅 2025-10-15    👤 surdeus    👁️ 1      

surdeus

// lib.rs
pub trait A: Private { }
trait Private { }

pub trait B: private::Private { }
mod private {
    pub trait Private { }
}

In this piece of code, how A is written is not recommended but B is recommended.

cargo building this warns about the trait A but not the trait B:

warning: trait `Private` is more private than the item `A`

How B is written is also recommended as "the sealed trait" pattern in Rust API Guidelines.

My question is, why is this the case? Both have the same effect of preventing A or B from being implemented outside of the crate/module, and keeping the Private trait's interfaces private. At the same time, B is obviously more verbose and less intuitive (I would not think of using the B pattern or think of that B will not trigger the warning that A does without getting to the API Guidelines). Yet B is the recommended way.

3 posts - 3 participants

Read full topic

🏷️ Rust_feed