When is code unsafe
There are situations in which even the Rust compiler cannot guarantee that our code will behave in a safe manner. This could occur when:
- We need to program against the metal, close to the operating system, processors, and hardware
- We want to work with the same amount of control as is possible in C
- We delegate a part of the program execution to an unsafe language, such as C
- We want to use inline assembly language
Rust allows us to do all of these, but we have to envelop this possibly dangerous code in an unsafe
block:
unsafe { // possibly dangerous code }
This means that the programmer takes full responsibility for the code in the block. The unsafe block is a promise to the compiler that the danger does not leak out of the block. The compiler will check the code areas marked as unsafe
more loosely and allow otherwise forbidden manipulations, but a number of rules in the ownership system (see Chapter 7, Ensuring Memory Safety and Pointers) still remain in place.
The clear...