3 ms·
>>I much prefer Rust's approach of "mutable references never alias" >This rules out a vast majority of fundamental algorithms. To be more precise, in Rust: -
by ekidd 8y ago
>>I much prefer Rust's approach of "mutable references never alias"
>This rules out a vast majority of fundamental algorithms.
To be more precise, in Rust:
- '&mut T' (a mutable reference to T) can never alias.
- '(asterix) mut T' (a mutable pointer to T) can alias.
The advantage is that you can write most production code with a mix of '&T' and '&mut T', which allows the compiler to assume no mutable aliases anywhere. But if you're building a doubly-linked list, then you can explicitly choose '(asterix) mut T'. (For other options, see https://rust-unofficial.github.io/too-many-lists/. https://rust-unofficial.github.io/too-many-lists/.)
In practice, it depends a lot on the code you're writing. I've written tens of thousands of lines of production Rust without needing shared mutability. But if I were writing a traditional game or GUI toolkit, then I might miss shared mutability a lot more.
- hedora 8y agoThe & semantics sound like fortran’s semantics. How does the rust compiler know if two references passed in from calling code can alias or not? (I.e., what if I get the type annotations wrong?). In general, determining if two pointers can alias is equivalent to the halting problem. The default C way is “assume aliasing unless you can prove otherwise”. This seems safer and like less work to me.
- wwright 8y agoAliasing is checked in the calling code, not the callee. You’re not allow to create a mutable reference if another exists in the same scope. If you use “plain” safe Rust, there’s simply just no way to create alias mutable references unsafely. (The C default you refer to is at the compiler internals level. The Rust alias prevention we’re talking about is at the language level. C compilers will try to avoid generating code that will behave incorrectly in the presence of aliasing, but do nothing to prevent aliasing and the possible logic and thread safety issues caused by aliasing. Rust makes almost all of these cases disappear for the programmer.)
- Ar-Curunir 8y agoThe compiler ensures that you can only take one &mut reference at a time. You can have as many immutable `&` references as you want, because you can't change anything through those references (unless you do some unsafe trickery)
- cesarb 8y ago> you can only take one &mut reference at a time. You can have as many immutable `&` references as you want There's another small detail: these two cases are mutually exclusive. You can either have one &mut reference, or as many & references as you want. This means that code receiving a & reference can be sure the object won't change, and that code receiving a &mut reference knows the object can be modified safely since nothing else could be looking at it. (Assuming the object doesn't contain a Cell, the rules are a bit different when a Cell is involved.)