2 ms·
Usage of `unsafe` generally has to do with subverting the Rust compiler's notion of ownership. Take a look at this snippet from the OP discussing the usage of u
by kibwen 11y ago
Usage of `unsafe` generally has to do with subverting the Rust compiler's notion of ownership. Take a look at this snippet from the OP discussing the usage of unsafe code in the client example:
> The operation is unsafe because it is asserting that:
> * the Shared pointer is not reachable from the data structure,
> * no other thread will call unlinked on it.
This is only necessary because the library here is concerned with sharing a data structure among multiple owners (the owners being threads in this case) who all wish to mutate the data structure.
There are other places like this where one may wish to subvert the borrow checker, and when such a pattern becomes widely observed it can be placed in the standard library behind a safe interface, (ideally) removing the need for unsafety in client code entirely. The `Rc` smart pointer in the stdlib is one such example of a safely-exposed interface to code that internally uses unsafety to subvert ownership in a specific way. And as long as you trust the compiler to be correct, you can also trust that the "unsafe" code in the stdlib is also correct (or at the very least that the Rust developers are guaranteed to fix any incorrectness that is found).
- unfamiliar 11y agoI understant those concepts. My question was more along the lines of, could the code you mention from the article one day be written without unsafe? Somehow the programmer is very confident that neither of the two restrictions you mention will be broken. Is there any way that it can be proven from the code that they will not be broken, and therefore remove the need for unsafe? Or, if safety can not be proven from the code, how is the programmer so certain of it?