3 ms·
Yes, you can do it, with Cell and RefCell, though the former is restricted to POD types and the latter comes with some minor runtime overhead. Inherited mutabi
by pcwalton 13y ago
Yes, you can do it, with Cell and RefCell, though the former is restricted to POD types and the latter comes with some minor runtime overhead.
Inherited mutability is not an unnecessary restriction from the point of view of memory safety. It's critical to Rust's ability to prevent iterator invalidation and related bugs at compile time. The fact that C++ doesn't do it is the source of many of its memory safety problems, such as dangling references and iterator invalidation.
- pohl 13y agothe former is restricted to POD types I had to look this acronym up. In case anybody else needs a definition: https://en.wikipedia.org/wiki/Plain_Old_Data_Structures https://en.wikipedia.org/wiki/Plain_Old_Data_Structures
- gilgoomesh 13y agoWithin context (the article is for C++ programmers) POD is a commonly used acronym. If you're a C++ programmer and don't know about POD types (data types with zero implicit C++ behaviors), you should brush up on your fundamentals – it's essential to understand when and why C++ behaviors (i.e. behaviors above and beyond plain C) are invoked implicitly.
- Peaker 13y agoI was a bit surprised by the reverse: let x = 5 let mut y = &x If I understood correctly, x is immutable, but can still be mutated via (*y)?
- pcwalton 13y agoNo, that results in an error. Mutability doesn't inherit through references (`&`).
- coderjames 13y ago[disclaimer: still learning Rust] I believe it actually means that y can be made to reference something other than x. let x = 5 let mut y = &x let i = 13 y = &i This is similar to C++'s const-pointers and pointers-to-consts, where either a pointer cannot be made to point at something different or the pointer cannot be used to change what it points at.
- FreeFull 13y agoThat actually lets you change what y points at, but you can't mutate x through y. If you want to mutate x, you need something like let y = &mut x; which will result in an error due to x not being mutable.