3 ms·
> To me, this somehow says that most truely interesting problems can only be solved efficiently in Rust using unsafe. Even Vec is implemented with unsafe code
by pcwalton 7y ago
> To me, this somehow says that most truely interesting problems can only be solved efficiently in Rust using unsafe.
Even Vec is implemented with unsafe code under the hood. Rust isn't about not using unsafe code anywhere: it's about encapsulating that unsafe code in reusable abstractions that can be easily audited. This is how essentially all languages work to begin with: unless you're using CompCert, the compiler itself is not proven correct, and so the compiler's code generator is "unsafe".
Here's an example of how rav1e, an AV1 encoder in Rust, builds safe abstractions out of unsafe primitives in order to solve a similar problem: https://blog.rom1v.com/2019/04/implementing-tile-encoding-in-rav1e/ https://blog.rom1v.com/2019/04/implementing-tile-encoding-in...
- gmueckl 7y agoWait, so how exactly is Rust better than C++ again? If I need to bring my own unsafe code to the party, where is the gain? Especially, if - in your words - "This is how essentially all languages work to begin with". I can build "safe" abstractions in any other language, too, can I not?
- CUViper 7y agoIn other languages, nothing ensures that those safe abstractions are actually used in safe ways. You can keep a dangling reference to a C++ vector, but Rust will make sure your references are valid, and you can only escape that with raw pointers in an unsafe block.
- unrealhoang 7y agoC++ doesn't have the tool to do so. Just like you can build abstraction for raw data in any language, but only the compiler in static typed language will scream at you at compile time if you use it the wrong way and dynamic language will just believe you will do the right thing.
- eridius 7y agoIn general you don't need to bring your own unsafe code to the party. The standard library contains most of the unsafe code you'll need to use in your normal code, and a handful of well-supported crates (like rayon) provide the more advanced utilities that the standard library doesn't. In most cases you're only writing `unsafe` if you're interacting with C. And when you do decide you need to use `unsafe` for a non-FFI purpose, Rust provides the tooling to explicitly define the abstraction barrier such that clients of your code don't have to care (or even know) that you're using unsafe internally.
- pcwalton 7y agoNo, you can't build safe abstractions in C++. The language lacks the ability to enforce memory safety. Every abstraction you can come up with will have some way to subvert it. In Rust, the abstractions can't be broken without using unsafe, which application logic should never use. This isn't just a theoretical distinction. Empirically, Rust programs have far fewer memory safety problems than C++ programs do.