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_uncheckedmethod on slices, which requires callers to verify that the index is in-bounds. - unsafe traits (
unsafe trait). Examples:SendandSyncmarker 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_sectionandno_mangle. Usage:#[unsafe(no_mangle)]