Document unsafe Rust code by adding a SAFETY comment explaining the specific invariants that make the operation safe.
Document unsafe code by adding a // SAFETY: comment immediately before the unsafe block that explains why the operation is safe. This comment must detail the invariants you are upholding, such as valid pointers or non-aliasing references, to satisfy the compiler and future maintainers.
// SAFETY: `ptr` is a valid, non-null pointer to a `T` that was allocated
// by `Box::new` and is not aliased by any other pointer in this scope.
unsafe {
let value = ptr.read();
}
Unsafe code in Rust bypasses the language's safety checks to allow low-level operations like direct memory access. You must document these sections to prove to other developers that you have manually verified the code won't crash or corrupt memory. Think of it like a mechanic explaining exactly why they removed a safety guard on a machine; without that explanation, no one else should touch it.