2 ms·
You're on the right track. Rust has a type called Cell [1] (not to be confused with RefCell), which is just a wrapper around T with no overhead. Cell has what
by comex 8y ago
You're on the right track. Rust has a type called Cell [1] (not to be confused with RefCell), which is just a wrapper around T with no overhead. Cell has what Rust calls "interior mutability", which means you can both read and write the contained value using a nominally immutable reference. This is safe within Rust's type system because it doesn't let you get a reference to the contained value (which could then become dangling), only move the whole value in and out. It's also not safe to use from multiple threads, since data races are UB in both Rust and C (to do that properly you'd need to use atomics); but Rust automatically prevents you from sharing references to Cells across threads (because Cell is marked as !Sync).
Anyway, in practice Cell can be used to wrap individual fields of basic data types, e.g. Cell<u32>, and you effectively have an aliasable mutable field. For such types, the inability to get a reference to the interior doesn't really matter, since there's rarely a reason to take a reference rather than just copying the value. However, the syntax is pessimized: you have to do field.get() and field.set(val) instead of getting and setting the field normally. In theory, this could be built into the language (rather than being mostly a library feature) and it could be quite a bit nicer; I remember seeing that proposed at least once. The reasons it hasn't happened so far are, I think, at least partly philosophical.
(edit: This can also be used for your vector example, as you can have a Vec<Cell<u32>>.)
[1] https://doc.rust-lang.org/nightly/std/cell/struct.Cell.html https://doc.rust-lang.org/nightly/std/cell/struct.Cell.html