Unsafe operations and safety contracts
Quick answer
Unsafe Rust permits specific operations that the compiler cannot fully verify. The programmer must establish their safety conditions; ordinary typing and borrowing rules still apply.
Keep the unsafe region small
An unsafe function can require caller obligations, while an unsafe block states that its operations satisfy their preconditions. In edition 2024 use explicit unsafe blocks inside unsafe functions too; the unsafe_op_in_unsafe_fn lint warns otherwise by default. Prefer safe indexing and iterators unless a justified invariant requires a lower-level operation. Unsafe does not make undefined behavior acceptable.
fn main() { let values = [10, 20]; println!("{:?}", values.get(1)); }Expected stdout (not executed):
Some(20)get checks the bounds.
fn main() { let values = [10, 20]; // SAFETY: index 1 is in bounds of this initialized array. let n = unsafe { values.get_unchecked(1) }; println!("{n}");}Expected stdout (not executed):
20The known array length proves the index is valid. In ordinary code use get or indexing instead.
Common mistake
Never add an unsafe block merely to silence a diagnostic without establishing the relevant invariant.
Try it yourself
Explain why index 2 is not permitted in the second example; do not execute an out-of-bounds unsafe access.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Unsafe operations and safety contracts — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
An unsafe block calls get_unchecked. Who must establish the index is in bounds?
Unsafe operations and safety contracts — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn main() { let values = [10, 20]; println!("{:?}", values.get(1)); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Unsafe operations and safety contracts — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn main() { let values = [10, 20]; // SAFETY: index 1 is in bounds of this initialized array. let n = unsafe { values.get_unchecked(1) }; println!("{n}"); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.