Is that a chiasmus?
So, as per the current definition of Rust the language, a
&mut reference is a unique one, per definition (FWIW, at some instances it was suggested it be called
&uniq, precisely because people reasoning about it as a mutable reference rather than as a unique one were not understanding the language correctly). Violating its uniqueness guarantee goes against its very definition in the language, thus representing a "contract violation" w.r.t. the compiler guarantees, i.e., the very definition of UB.
That being said, you can very legitimately ask about the rationale behind this design / ask if the restrictions could be loosened. To think about the pros and cons of replacing
&uniq in the language with
&cell (and at that point, replace
& _ with
&cell _ as well, and we'd have C++-like references):
pro: it simplifies a bit the mental model, by not having to worry about aliasing.
con: by now having to deal with aliased mutability, writing some code in a bug-free no-matter-the-API-misusage manner becomes more complex1 at best, or more difficult, or even straight up impossible. To avoid the memory-unsafe bugs of languages such as C/C++, a global gc becomes highly advisable, and we are back to being a gc / managed language, such as Python, Kotlin, go, etc.
- Another option is to get rid of mutability, since it plays so poorly with aliasing. This comes at the price of more copying, or usage of more complex data structures to palliate that. Rust becomes a functional language (OCaml, Haskell, etc.)
1 yet another chiasmus
Granted, having to produce
&uniq references can be demanding, at times, but in practice not that often (otherwise Rust would not be language one could be productive with!). But let's not overlook the power, the peace of mind, that being given
&uniq references, or, by contraposition, being given
&shared references that happen to imply immutability of the referee, both offer.
Vec's ptr/len/cap fields are immutable when referred to by a shared reference, thus making
&mut Vec<_> the only way one can append an element to the vec, potentially modifying the
*ptr allocation, it immediately follows that yielding
&'shared Elem references to the
Elements when given a
&'shared Vec<Elem> is something safe to do, and which no API misusage can break whatsoever.
Designing correct and robust code, that is, way less buggy code, becomes way easier in Rust thanks to that. That's why I wouldn't be surprised that the language with which mid-to-long term code is written and where the maintainers of such code are most productive turned out to be Rust (and functional languages; but that's where Rust efficiency (by not having to deal with the optimized immutable collection shenanigans from functional languages) might outshine those).
The power that comes from
&shared often meaning
&immutable) is one of Rust greatest strengths
I'm tempted to inverse-quote uncle Ben, and say: