Best Practices for Unsafe Code in Rust

Minimize unsafe blocks, isolate them in dedicated modules, and document the specific safety invariants they uphold to maintain Rust's memory guarantees.

Minimize unsafe blocks, isolate them in dedicated modules, and document the specific safety invariants they uphold. Use unsafe only when interacting with external code, performing raw pointer arithmetic, or calling other unsafe functions, ensuring the compiler's safety guarantees are manually verified before execution.

unsafe fn read_raw_pointer(ptr: *const i32) -> i32 {
    // SAFETY: We guarantee ptr is valid, initialized, and not moved.
    *ptr
}