Rust sealed traits — limiting who can implement your trait

I was bumping dependencies on an older OAuth2 axum koan project; the newer oauth2-rs uses sealed traits in a way that’s easy to miss if you only read the public API.

Use this pattern when you want your trait to control who is allowed to implement it.

A normal trait is wide open: anyone can add an impl for any type.

For example, nosealed_trait below can be implemented for both usize and i32:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
mod nosealed_trait {
pub trait MyTrait {
fn my_sealed_method(&self);
}
}
impl nosealed_trait::MyTrait for usize {
fn my_sealed_method(&self) {
println!("MyTrait for usize");
}
}

impl nosealed_trait::MyTrait for i32 {
fn my_sealed_method(&self) {
println!("MyTrait for i32");
}
}

What if you only want i32?

Have your public trait inherit a non-exported supertrait, and only implement that supertrait for the types you allow:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
mod sealed_trait {
mod private {
pub trait Sealed {}
impl Sealed for i32 {}
}
pub trait MySealedTrait: private::Sealed {
fn my_sealed_method(&self);
}
}

impl sealed_trait::MySealedTrait for i32 {
fn my_sealed_method(&self) {
println!("MySealedTrait for i32");
}
}

If a caller tries to implement your trait for a type that is not on the allow list, the compiler stops them:

1
2
3
4
5
impl sealed_trait::MySealedTrait for usize {
fn my_sealed_method(&self) {
println!("MySealedTrait for usize");
}
}

The error message spells it out in the note:

note: MySealedTrait is a “sealed trait”, because to implement it you also need to implement sealedtrait::private::Sealed, which is not accessible; this is usually done to force you to use one of the provided types that already implement it

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
error[E0277]: the trait bound `usize: Sealed` is not satisfied
--> src/main.rs:34:37
|
34 | impl sealedtrait::MySealedTrait for usize {
| ^^^^^ the trait `Sealed` is not implemented for `usize`
|
= help: the trait `Sealed` is implemented for `i32`
note: required by a bound in `MySealedTrait`
--> src/main.rs:23:30
|
23 | pub trait MySealedTrait: private::Sealed {
| ^^^^^^^^^^^^^^^ required by this bound in `MySealedTrait`
= note: `MySealedTrait` is a "sealed trait", because to implement it you also need to implement `sealedtrait::private::Sealed`, which is not accessible; this is usually done to force you to use one of the provided types that already implement it
= help: the following type implements the trait:
i32

Next: the typestate pattern.

Questions? Leave a comment below or email: newbvirgil@gmail.com