3.36. unsafe

Unsafe

Rust’s main draw is its powerful static guarantees about behavior. But safety checks are conservative by nature: there are some programs that are actually safe, but the compiler is not able to verify this is true. To write these kinds of programs, we need to tell the compiler to relax its restrictions a bit. For this, Rust has a keyword, unsafe. Code using unsafe has fewer restrictions than normal code does.

Let’s go over the syntax, and then we’ll talk semantics. unsafe is used in four contexts. The first one is to mark a function as unsafe:

# #![allow(unused_variables)]
#fn main() {
unsafe fn danger_will_robinson() {
    // Scary stuff...
}

#}

All functions called from FFI must be marked as unsafe, for example- The second use of unsafe is an unsafe block:

# #![allow