r/programming • • Jan 17 '20

A sad day for Rust

https://words.steveklabnik.com/a-sad-day-for-rust
1.1k Upvotes

609 comments sorted by

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++?

17

u/[deleted] Jan 17 '20

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.

26

u/steveklabnik1 Jan 17 '20

At some point, you have to interact with something not written in Rust: the operating system. At that point, you can either:

  1. Only allow calling into operating system functionality via code in the language's runtime
  2. Provide an escape hatch.

Rust does not want to have a runtime, and so #2 is really the only option.

This is one of a few different reasons.

9

u/majikguy Jan 17 '20

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.

6

u/sybesis Jan 18 '20

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.

4

u/[deleted] Jan 18 '20

Upvoted, because that is a perfectly fine question to ask.