4 ms·
> There is a workaround called "internal mutability", an ability to mutate state pointed by a shared pointer. That is syntactically slightly messier, and genera
by _dh54 4y ago
> There is a workaround called "internal mutability", an ability to mutate state pointed by a shared pointer. That is syntactically slightly messier, and generally frowned upon.
I don’t see why this would be frowned upon. It seems to be a runtime version of the borrow checker. For sufficiently dynamic code I don’t see how you can get around checking mutability access at runtime (or asserting that multiple blocks of code aren’t concurrently requesting a mutable reference).
As a comparison, there are many cases where the compiler can prove that a bounds check is unnecessary for accessing an element in a vector but there are also many useful cases where it’s simply not possible to do at compile time. It would be silly to frown upon runtime bounds checks when the requested index or the size of the vector is not known at compile time, a common occurrence in many interesting programs.
I get the motivation to make APIs as statically checkable as possible but it doesn’t seem to always be practical. Reusable UI components can be used in a variety of contexts, e.g. situations with multiple callbacks for different backends. The information is just not always there at compile time.
- jcelerier 4y agoAs someone who had literal paid gigs in c++ where I had to remove all sorts of reference counts to reach performance targets, it's depressing that there doesn't seem to be a better way in rust
- CyberRabbi 4y agoThe way to do this in Rust is to use “unsafe.” It essentially means “trust the programmer that this pointer is live.” I don’t think there is a way around this. You’re dealing with a high-level runtime condition. There are no tractable ways to get compilers to understand these higher level runtime conditions, so conditions must be reproven at runtime. It needs an oracle. That oracle should be you but you’ve decided that you cannot be trusted. This appears to be somewhat of a contradiction. Should you even be writing this program in the first place?
- GolDDranks 4y agoThe reason it's frowned upon is that it makes the code not thread safe. This is fine in application code, but if you are a library author, you generally want your code to be as flexible as possible, and able to be used in various situations. Making the code not thread safe brings upon some limitations how the code can be used by your users. This is why using internal mutation sparingly is the default.
- CyberRabbi 4y agoI’m not clear on what you mean it’s not thread safe. Arc<> is thread safe.