4 ms·
AIUI, Rust can do it "the Swift way" (a misnomer, since it was first) for any given object simply by adding a RefCell<…> or Mutex<…> type constructor, as approp
by zozbot123 8y ago
AIUI, Rust can do it "the Swift way" (a misnomer, since it was first) for any given object simply by adding a RefCell<…> or Mutex<…> type constructor, as appropriate. These types are commonly used in combination with reference-counting smart pointers, Rc<…> or Arc<…>. (The smart pointers focus on making the "multiple ownership" aspect work, but this entails that these types have to return shared references, which are ordinarily read-only. The RefCell or Mutex type constructors then focus on enabling "runtime-checked exclusive access" on top of the native, shared reference types).
- comex 8y agoThe problem with RefCell/Mutex is granularity. If you wrap the entire object in one of them, the mutable borrow you need to write a field blocks anyone else from accessing the object at all, even to read unrelated fields. Note that Swift 5 exclusivity enforcement is imposing exactly this limitation on Swift "structs", but not its heap-allocated "classes". In Rust, an alternative is to wrap individual fields in RefCell/Mutex, but that results in uglier syntax – you end up writing RefCell/Mutex and .borrow()/.borrow_mut() a lot of times – and adds overhead, especially in the Mutex case (since each Mutex has an associated heap allocation). There are alternatives, like Cell and Atomic*, that avoid the overhead, but have worse usability problems. I've long thought Rust has room for improvement here...
- raphlinus 8y agoYou can get rid of the heap allocation for Mutex by using parking_lot, and there is work to merge this into standard library. The rest of what you wrote sounds right to me.