🦀 Rust Advanced

What are the rules for writing correct unsafe Rust?

Answer

Writing correct unsafe Rust requires manually upholding invariants that the compiler normally enforces. Key rules: Never create undefined behavior — Rust's UB rules mirror C's: no data races, no use-after-free, no out-of-bounds access, no null dereferences, no violating Rust's aliasing rules (no &T and &mut T to the same memory simultaneously). Validate all unsafe preconditions — document them clearly with // SAFETY: comments explaining why the code is sound. Minimize unsafe surface area — wrap unsafe code in safe abstractions and audit the boundary. Uphold Send/Sync requirements — only implement these manually if your type truly satisfies the thread-safety invariants. Use tools like Miri (Rust's interpreter that detects UB in unsafe code), sanitizers (-Z sanitizer=address), and cargo audit to verify unsafe code correctness.