Hacker News new | ask | show | jobs
by ogoffart 744 days ago
Unsafe is still needed in some cases to access low-level APIs or to talk to the hardware. It can still be safe because that is limited in scope, and still makes the whole product easier to review.
1 comments

Pardon me as an outsider, but the primary selling point of Rust is exhaustive automated compile-time safety checking. If this promise is false, then Rust needs more work.
You’re asking for something that is literally impossible.
Before Rust, in the early age of C, even Rust would've have been considered impossible. But is it really mathematically impossible? Even if it were, surely some bounds can be placed in the code on the damage that unsafe Rust can cause, but do such bounds exist? Even Zig has features to control the damage.
Most usages of `unsafe` are necessary because of FFI calls into code written in C, into syscalls, into hardware memory-mapped regions, or other things outside of Rust's control. Without this ability, Rust wouldn't be able to call itself a systems language.

There are also some usages of `unsafe` for constructs (like linked lists) that the borrow-checker does not support. Those could theoretically be checked, but as far as I know a practical/pragmatic way of doing that has yet to be invented.

Every programming language has parts like Rust’s unsafe. In managed languages, that code is contained in the runtime, or in FFI.

In a practical sense, in order to not have “unsafe” code, the language specification would have to contain a full formal specification of every aspect that it’s running on. The hardware, the system software you rely on, everything. That isn’t a good idea, so no language does it. And it doesn’t help you when new hardware comes out.

In a more formal sense, you run into things like Rice’s theorem.

> Every programming language has parts like Rust’s unsafe.

This is a pretty weak argument. "Everyone else does it, so it's not wrong." If using this argument, Rust shouldn't even exist.

Rice's theorem seems handwavy in the real-world limitations of its restrictions. For the sake of argument, even Python is more memory-safe than unsafe Rust.