←back to thread

205 points michidk | 1 comments | | HN request time: 0s | source
Show context
dextrous ◴[] No.41836789[source]
I am a C/C++ dev learning Rust on my own, and enjoying it. I am finally starting to enjoy the jiu jitsu match with the compiler/borrow-checker and the warm “my code is safe” afterglow … but I have a question for the more experienced Rust devs out there, particularly in light of the OP’s observation about “lots of unsafe” in the Rust embedded realm (which makes sense).

If your Rust project leans heavily on unsafe code and/or many libraries that use lots of unsafe, then aren’t you fooling yourself to some degree; i.e. trusting that the unsafe code you write or that written by the 10 other people who wrote the unsafe libs you’re using is ok? Seems like that tosses some cold water on the warm afterglow.

replies(3): >>41836851 #>>41836872 #>>41846831 #
danhau ◴[] No.41836851[source]
Yes, safe Rust is only as safe as the underlying unsafe code is.

The power of unsafe is that it‘s opt-in, making the surface area of „dangerous“ code smaller, more visible and easier to reason about.

As long as the unsafe parts are safe, you can rest assured that the safe parts will be safe too.

replies(2): >>41837019 #>>41839052 #
iTokio ◴[] No.41837019[source]
Another way to see the benefit of this approach is that if you have a memory violation, then you only have to look in the unsafe blocks.

So, yes the less numerous they are, the more you gain from it.

replies(1): >>41843936 #
1. inahga ◴[] No.41843936[source]
> Another way to see the benefit of this approach is that if you have a memory violation, then you only have to look in the unsafe blocks.

Not really. Safety is non-local. It is possible to break unsafe code by feeding inputs from safe Rust that don't uphold the invariants that make the unsafe code safe. So it's not enough to look in the unsafe blocks--you have to consider the all the contexts that invoke the unsafe code.

See https://doc.rust-lang.org/nomicon/working-with-unsafe.html, and https://notgull.net/cautionary-unsafe-tale/ for a practical example.