Rust unsafe
Purpose
Guide agents through writing, reviewing, and reasoning about unsafe Rust: what operations require unsafe, how to write safe abstractions, audit patterns, common pitfalls, and when to reach for unsafe.
Triggers
- "When do I need to use unsafe in Rust?"
- "How do I write a safe abstraction over unsafe code?"
- "How do I audit an unsafe block?"
- "What are the rules for raw pointers in Rust?"
- "What does transmute do and when is it safe?"
- "How do I implement UnsafeCell correctly?"
Workflow
1. The five unsafe superpowers
unsafe grants exactly five capabilities not available in safe Rust:
- Dereference raw pointers (
*const T,*mut T) - Call unsafe functions (including
extern "C"functions) - Access or modify mutable static variables
- Implement unsafe traits (
Send,Sync) - Access fields of unions
Everything else in Rust — including memory allocation, borrowing, closures — follows safe rules even inside unsafe blocks.
2. Raw pointers
Rules for sound raw pointer dereference:
- Pointer must be non-null
- Pointer must be aligned for
T - Memory must be initialized for
T - Must not violate aliasing rules (only one
&mutto a location) - Memory must be valid for the lifetime of the reference
3. unsafe functions and traits
4. Safe abstractions over unsafe
5. transmute
Common transmute pitfalls:
- Wrong sizes (compile error, but check for generic types)
- Creating invalid enum values
- Creating references with wrong lifetimes
6. UnsafeCell — interior mutability
7. Unsafe audit checklist
When reviewing an unsafe block:
- Is there a
// Safety:comment explaining the invariant? - Is the raw pointer non-null?
- Is the raw pointer correctly aligned for the target type?
- Is the memory initialized?
- Is the lifetime of the reference valid?
- Are aliasing rules respected (no simultaneous
&and&mut)? - For
extern "C": are C invariants documented and verified? - For
Send/Syncimpl: is thread safety actually guaranteed? - Is the unsafe block as small as possible?
- Is there a test under Miri for the unsafe code?
8. When to use unsafe
For unsafe patterns and audit examples, see references/unsafe-patterns.md [blocked].
Related skills
- Use
skills/rust/rust-sanitizers-miri— Miri is the essential tool for testing unsafe code - Use
skills/rust/rust-ffifor unsafe patterns in FFI contexts - Use
skills/rust/rust-debuggingfor debugging panics in unsafe code - Use
skills/low-level-programming/memory-modelfor aliasing and memory ordering in unsafe


