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.

Examples
This example shows how to document unsafe functions following best practices: This example uses the above function:

Writing unsafe code
If you think that you need to resort to, there are some things you should consider:


 * Read the article about Undefined Behavior and the relevant parts of the Rustonomicon and the Unsafe Code Guidelines.
 * When writing unsafe code, document it carefully.
 * Benchmark your code or look at the generated assembly, to verify that the unsafe code actually performs better than the equivalent safe code.
 * Ask other programmers for a code review.
 * Run your code in MIRI.
 * Add unit tests to your code.
 * Fuzz your code.