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 { pubtraitMyTrait { fnmy_sealed_method(&self); } } implnosealed_trait::MyTrait forusize { fnmy_sealed_method(&self) { println!("MyTrait for usize"); } }
implnosealed_trait::MyTrait fori32 { fnmy_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 { pubtraitSealed {} implSealedfori32 {} } pubtraitMySealedTrait: private::Sealed { fnmy_sealed_method(&self); } }
implsealed_trait::MySealedTrait fori32 { fnmy_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
implsealed_trait::MySealedTrait forusize { fnmy_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