Unsafe

Rusts safety guarantees can be limiting when writing low-level code, because they prevent you from doing potentially dangerous things. Unsafe Rust allows you to sidestep some of these restrictions.

Unsafe Rust is very dangerous and can cause undefined behavior (UB). Because of this, it is always marked with the keyword. This makes it clear which parts of the code must be carefully vetted for safety. Furthermore, many Rust programs don't use  at all. It is good practice to always add a comment to  code, which explains why the code is safe, or what is required to use it safely.

Note that  code is not allowed to violate Rusts safety guarantees. If  is used, it's the programmer's responsibility to prevent undefined behavior, although the compiler can't verify this.

Unsafe Operations
Using, it is possible to perform the following operations, which are not allowed elsewhere:


 * Dereference
 * Call  functions (including C functions, compiler intrinsics, and the raw allocator)
 * Access or modify a mutable static variable
 * Access fields of unions
 * Implement  traits

Unsafe Contexts
An unsafe context is a context where the unsafe operations are allowed:


 * blocks within a function introduce a scope with an unsafe context.
 * functions currently introduce an unsafe context as well, but this will be changed in the future.
 * traits are implemented by writing.

Implications for safe code
When  code is used incorrectly, it can cause UB; we call such code unsound. Unfortunately, even safe code can be unsound, if it somehow relies on an unsound API. This means that incorrect usage of  can cause problems in different parts of the code and even different crates.