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
andSync
marker traits in the standard library.
Places where pre-conditions must be satisfied (Role 2)
- unsafe blocks (
unafe { ... }
) - implementing unsafe traits (
unsafe impl
) - access external items (
unsafe extern
) - adding unsafe attributes o an item. Examples:
export_name
,link_section
andno_mangle
. Usage:#[unsafe(no_mangle)]