4 ms·
I'm not very familiar with rust, but isn't the point to mostly avoid `unsafe` and write safe code? Strange that basic std vec functions like insert and remove c
by ativzzz 3y ago
I'm not very familiar with rust, but isn't the point to mostly avoid `unsafe` and write safe code? Strange that basic std vec functions like insert and remove call `unsafe` - isn't this an example where you don't want to be like the std lib?
- josephg 3y agoAt the end of the day, rust is still a systems language. Lots of useful things require unsafe, including most data structure implementations and FFI - including syscalls. I see rust's safety guarantees like having a good static type system. Static type systems don't claim to prevent all bugs, but they do catch an awful lot of bugs at compile time in practice. Rust's default safety with opt-out unsafe blocks work the same way. Despite what some zealots would have you believe, the point isn't to make every single line of code "safe". Good rust code still uses unsafe code - for example your binary includes unsafe code whenever you use Vec or Box from std. But all unsafe code blocks are explicitly called out as such, tested thoroughly (eg with miri) and usually constrained to a small part of your program. You can think about it as, C or C++ programs are 100% unsafe. Rust programs are usually only ~2% unsafe or so. That makes a huge difference in practice. Unsafe code can also usually be encapsulated in safe wrappers. (Eg std::io::File wraps the unsafe call to open(), and std::Vec wraps some raw pointer operations). Unsafe also doesn't turn off the borrow checker. The only difference is unsafe blocks allow you to dereference pointers, call unsafe functions, and a few other things like that.
- steveklabnik 3y ago> Strange that basic std vec functions like insert and remove call `unsafe` The standard library has more unsafe than most programs, because "data structures that need a lot of unsafe" has historically been an argument for being put in the standard library, because that way they'll be reviewed very carefully by experts.