When is unsafe used?

The unsafe keyword indicates that the programmer is responsible for upholding Rust’s safety guarantees.

The keyword has two roles:

  • define pre-conditions that must be satisfied
  • assert to the compiler (= promise) that those defined pre-conditions are satisfied

Further references

This slide should take about 2 minutes.

Places where pre-conditions can be defined (Role 1)

  • unsafe functions (unsafe fn foo() { ... }). Example: get_unchecked method on slices, which requires callers to verify that the index is in-bounds.
  • unsafe traits (unsafe trait). Examples: Send and Sync marker traits in the standard library.

Places where pre-conditions must be satisfied (Role 2)