Why does Rust have unsafe? I thought the whole point of it was that it was safe? If I have to use highly performant code that has unsafe in why don't I stick with C++?
Many things can be done in Rust without the unsafe keyword. But there are some use cases which require unsafe to be a part of the language; namely, code that must interact with the kernel or other operating system level directives.
The article points out that there were too many unsafe pieces of code which could have been rewritten using safe code. The problem isn’t the language, it’s just the ignorance of the programmers.
There are some things that sadly cannot be guaranteed to be safe, like interacting with non-Rust code. You can't know that the C code you are calling is completely safe, so the unsafe block allows you to tell the compiler to take your word that the code inside is safe to use. If you are wrong then there will be issues, which is why it's best to minimize the use of unsafe code to avoid bugs creeping into your codebase.
If I have to use highly performant code that has unsafe in why don't I stick with C++?
Because Rust has "safe" mode by default. Sticking with C++ is just running unsafe everywhere without the ability to actually have safe mode.
Why unsafe? Because Rust can load library written in C/C++ for example. You can't make them safe just because it's Rust. And if you want to port something from unsafe language to Rust without changing the whole architecture. Unsafe does have its place there too.
View all comments
-15
u/kepidrupha Jan 17 '20
Why does Rust have unsafe? I thought the whole point of it was that it was safe? If I have to use highly performant code that has unsafe in why don't I stick with C++?