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"); } }
如果调用方想实现不在限定实现列表中的方法就会被编译错误阻止。
1 2 3 4 5
implsealed_trait::MySealedTrait forusize { fnmy_sealed_method(&self) { println!("MySealedTrait for usize"); } }
错误如下, 其中的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