4 ms·
unsafe exists in Rust for when you need it. When it is used, it means nothing more than you’re writing code for which you must ensure the safety instead of the
by bluejekyll 8y ago
unsafe exists in Rust for when you need it. When it is used, it means nothing more than you’re writing code for which you must ensure the safety instead of the compiler.
The times when unsafe is poorly used are when it’s being abused to ignore safety related compilation issues, like lifetimes and/or mutability. Though, even in those cases it might be ok if you’re using lower level concurrency primitives to enforce those guarantees.
unsafe does not remove all advantages of Rust, it only removes a few restrictions. It should be avoided unless necessary.
- steveklabnik 8y agoIt doesn’t remove restrictions, it adds unchecked constructs. Very different!
- bluejekyll 8y agoHm, I’m not sure I see the difference between those concepts, but I do like your framing better.
- lmkg 8y agoThe main point is that if you take safe code and put it inside an unsafe block, the meaning of the code doesn't change. So for example, array indexing is bounds-checked in safe code, and non-bounds-checked array access is only available in unsafe blocks. This does not mean that the call `a[i]` loses bounds-checking in an unsafe block. It has the same semantics regardless of context. Rather, the separate call `a.get_unchecked(i)` is available inside an unsafe block and cannot be called in safe code.
- steveklabnik 8y agoWhat my sibling said, but also, that unsafe doesn’t mean you’re free from rules; where safe and unsafe interact, your unsafe code is expected to uphold the safety guarantees that the safe code expects. This matters because of stuff like the article; if you see the other thread, I’m pretty sure (though haven’t verified yet) that this code has UB, even though they’re using unsafe.
- bluejekyll 8y agoRight, which is why I phrased it as a “few restrictions”, I do understand the point you’re making. I suppose the reason I consider it restrictions is due to things like “in safe code you can not work with raw pointers”. That seems like a restriction to me, but I can see why saying that way is less accurate.