Why unsafe keyword is needed?

When attempting to compile code that contains unsafe operations, the 'unsafe' keyword is required and a warning is issued. The compiler knows what is unsafe in the code, so why do programmers need to explicitly include the 'unsafe' keyword in the code?
スクリーンショット 2023-11-09 2.14.31

The unsafe {} block is a safety device, like a cover over a button that keeps you from accidentally pushing it without lifting the cover. It assures the writer of the code that if they don't write unsafe, they don't need to worry they're doing something unsound.

Also, the unsafe block is mandatory documentation. It tells the reader of the code “something here needs careful attention”.

6 Likes

So that programmers (readers of the code) know it too.

3 Likes

Because that's a better default than people needing to say where they're trying not to use unsafe operations.

2 Likes

The compiler can't check the soundness of unsafe operations, so we use unsafe blocks to promise the compiler and other readers of the code that we did our homework and manually checked that what we are doing is sound.

If you haven't already, I'd recommend having a look at the Rustonomicon chapter 1. Meet Safe and Unsafe and following subchapters for a more pedagogical description of why things work the way they do in Rust.

3 Likes

Thank you for teaching me so kindly.
I found all of the responses helpful, so I would like to mark the answer from the person who replied first as 'Solution'.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.