Before we explain how and when to use (or not use) unsafe in Rust, I want to dispatch with a few persistent myths about unsafe code in Rust. No. The d

Unsafe Rust: How and when (not) to use it

submited by
Style Pass
2021-07-15 20:30:03

Before we explain how and when to use (or not use) unsafe in Rust, I want to dispatch with a few persistent myths about unsafe code in Rust.

No. The distinction is subtle, but safe Rust code cannot violate the safety guarantees, as long as neither the compiler nor the unsafe code it builds on have any bugs that allow this to happen. So, unlike other low-level languages, where the safety of the code rests on each line of code plus the compiler implementation, you can reduce the attack surface you need to audit for errors considerably.

The RustBelt project mathematically proved that if you have a portion of safe code and a portion of unsafe code that guards its invariants, the safe code cannot break the guarantees as long as the unsafe code doesn’t let it.

Statistically speaking, less than 1 percent of Rust code found on Crates.io — which is likely less than 50 percent of code out there, but should nevertheless be a sufficiently representative sample — is unsafe code, and many crates have no single unsafe line of code.

Leave a Comment