4 ms·
For each use of unsafe in Rust code, presumably the developer sees some safety guarantee that the compiler does not understand but that he thinks will guarantee
by unfamiliar 11y ago
For each use of unsafe in Rust code, presumably the developer sees some safety guarantee that the compiler does not understand but that he thinks will guarantee that the code is indeed safe. Can anyone shed light on what form these guarantees (that are not seen by the borrow checker) take, and whether it will be possible in future Rust versions to write such code without unsafe (either by improvements to the borrow checker or implementation of an additional safety checker)?
- kibwen 11y agoUsage 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?