I've run into a use case where I need to guarantee that an object is not mutated during its lifetime after it's created. This is beyond merely putting it behind a
& or in an
Arc as there is always the possibility of interior mutability gumming up the works. Basically, I need something like
const, but which has a non-
'static lifetime, which is also recursive through everything that the object owns for the duration of its lifetime. I thought about things like
OnceCell, but as its own documentation shows, it still permits interior mutability. I want to prevent that from happening at all.
This made me think about something like
Unpin that would declare that the object, once created, was permanently immutable for its lifetime. Let's call this marker trait
std::marker::Mutable. If an object is marked
Mutable, or any object it contains (including by reference) is
Mutable, then it is also marked as
Mutable. If the compiler cannot determine if an object is mutable or not, then by default it is
Mutable. Whatever is left over is immutable. Note that all of this done at compile time, not at runtime, which is why you can have code that the compiler can't prove is immutable, which is why it gets the
So, why bother? My hope is that the compiler team could take this information and use it to produce faster/better code. If you know for certain that something and all of its contents are
const for a given lifetime, can you (meaning the compiler team) produce faster/better code?
The biggest issue is how
unsafe code is dealt with. In theory, someone can transmute a
usize into a pointer to anywhere in memory, including to things that are supposedly immutable, and thereafter mutate it. My vote is to ignore this issue as
unsafe is unsafe for a reason; you're expected to know what you're doing, including knowing that if you mutate stuff that is supposed to be immutable, then you're in UB territory.
So, thoughts? I'm mainly interested in thoughts from the compiler team as the idea for this is driven by a need for speed. If it isn't likely to be useful in speeding up code, then there really isn't much point in pursuing it further.