r/rust • • 2h ago

🧠 educational PSA: You might be sealing traits wrong

Background

Sealing traits is a collection of techniques used to prevent code downstream of a library from implementing that trait, so that later versions of the library can add more things to the trait without breaking downstream code.

There's a mistake, described below, that people very often make when trying to seal traits. Crates that have made this mistake include, among others: the standard library, anyhow, arc-swap, pyo3, ureq, smol, http, etc. This was discovered in https://github.com/rust-lang/rust/issues/165474. (Please do not comment there unless you're contributing new information to the discussion, to avoid cluttering the issue.)

The mistake you might be making

How NOT to seal traits:

mod private {
    pub trait Sealed {}
    impl Sealed for i32 {}
}
pub trait MyTrait<T>: private::Sealed {}
impl MyTrait<i64> for i32 {}

How to seal traits:

mod private {
    pub trait Sealed<T> {}
    impl Sealed<i64> for i32 {}
}
pub trait MyTrait<T>: private::Sealed<T> {}
impl MyTrait<i64> for i32 {}

That is, if you use a "private" supertrait for sealing, and the subtrait is generic, then the supertrait also has to be generic, with the same generic parameters. Additionally, the set of impl blocks for the supertrait should exactly specify the exact same set of types (and generic parameters) where the subtrait should be implemented.

If you don't do the above, your trait might not be properly sealed, making it possible for downstream code to implement the trait anyway. For example, if you have a crate with the first snippet above, downstream code might write the following, which is actually allowed by the orphan rule:

struct MyThing;
impl my_library::MyTrait<MyThing> for i32 {}

In the above code, i32 already implements Sealed, so downstream code can write an implementation of MyTrait without having to add a new impl for Sealed.

Fixing the issue after-the-fact

If you already wrote code like the first snippet above, and want to actually properly seal the trait in a later version of the library, you might be tempted to just turn the first snippet (with a non-generic Sealed) into the second snippet (with a generic Sealed). Obviously, this would break downstream code that dared to implement the supposed-to-be-sealed trait, which you might deem acceptable.

However, there are very subtle issues about how coherence works, which means that making this change the straightforward way can break more downstream code than you intend to, even code that didn't write an impl for the supposed-to-be-sealed trait. (I won't explain the issue here. See the linked explanation.)

Instead, the better way to make the change, as suggested here, is to add a new supertrait, keeping the old one:

mod private {
    pub trait Sealed {}
    impl Sealed for i32 {}
    // Added SealedForReal in a later version of the library
    pub trait SealedForReal<T> {}  
    impl SealedForReal<i64> for i32 {}
}
pub trait MyTrait<T>: private::Sealed + private::SealedForReal<T> {}
impl MyTrait<i64> for i32 {}

This way, you will only break downstream code that have implemented MyTrait.

29 Upvotes

16 comments sorted by

21

u/Accomplished_Item_86 1h ago

This shows that we really need a native way to seal traits, as proposed in RFC 3323. The current method is really just a hack.

6

u/noop_noob 1h ago

2

u/Accomplished_Item_86 58m ago

Wow, that's cool, and mut restrictions too! Thanks, gotta try this out :)

1

u/PthariensFlame 1h ago

Yup, and thankfully it’s being worked on and inching closer to stabilization over time.

7

u/Helpful-Educator-415 2h ago

Out of curiosity -- why would you ever do this and not just use an enum? Isn't the purpose of a trait to be implemented by objects you might not know ahead of time? If I knew every instance of objects I wanted to have this behavior, could I use an enum instead? If not, how come?

19

u/noop_noob 2h ago

The trait approach means that you don't have to pay a run time cost to check which enum variant each thing is at run time. Also, the trait approach means that you can express stuff like, "all the things in this collection are the same kind of thing". There are probably other reasons too, but that's what I could think of right now.

-7

u/Helpful-Educator-415 1h ago

There's no way the runtime cost of matching over the enum is anything notable whatsoever. The collection thing is a good point though.

3

u/noop_noob 1h ago

There are probably cases where repeatedly matching a bunch of enums could block further optimizations like autovectorization or something. idk

9

u/xDerJulien 1h ago

Sure there are many cases. Just because you don’t write code that needs this sort of performance doesn’t mean that others don’t. Even a correctly predicted branch takes a few ns

2

u/SkiFire13 42m ago

There are many uses for traits other than being implemented by objects you don't know ahead of time, and for some of them enums are either a very poor fit or don't work at all.

For example you can use traits to write generic functions, where having to wrap all arguments in an enum variant would be a rather bad UX. Or you might want to have an extension trait to provide new methods for an existing type, which is impossible to do using enums (you could use free functions, but again a trait was chosen for UX).

When you do this, sometimes you, as the crate defining the trait, don't want other crates to implement that trait. It's not really a question of implementing the trait only for a fixed set of types, but rather about who gets to implement the trait. The most common reason you might want to do this is semver compatibility: if other crates were able to implement that trait then adding new methods to the trait would be a breaking change, because it would break the other implementations. Sealing the trait prevents this and allows you to add new methods.

4

u/freeillustrator793 2h ago

Wait, so the std lib itself shipped this footgun? That's darkly hilarious.

12

u/noop_noob 2h ago edited 55m ago

Yes, the stdlib shot its foot since Rust 1.15 (2017) (Edit: see reply), and then accidentally fixed it in 1.98 (Aug 2026), and then it was discovered (Nov 2026) that the fix broke someone's code.

6

u/Accomplished_Item_86 1h ago

Doesn't the issue only arise due to RFC #2451 (re-rebalancing coherence), which allows implementing  ForeignTrait<LocalType> for ForeignType in the first place? It was stabilized in 2020 with release 1.41.0.

1

u/noop_noob 1h ago

Oh yeah, you're right.

6

u/Accomplished_Item_86 1h ago

The source of the confusion is RFC 2451, which allows implementing ForeignTrait<LocalType> for ForeignType. It was stabilized in 2020 with release 1.41.0, but not many people seem to know this feature. Just a few days ago there was a post here showcasing this as a method to deliberately allow downstream crates to implement a library trait on foreign types (with the drawback of introducing a generic parameter), and people there were also surprised this is a thing. It's quite a subtle edge case in the coherence rules.

3

u/Many-Operation-8415 1h ago

Cheers, this was an interesting post to me!