25.14 Summary and Further Resources

Unsafe Rust allows you to step outside the bounds of safe Rust, enabling low-level programming and direct hardware interaction. However, with these capabilities come responsibilities: you must manually guarantee memory safety, freedom from data races, and other critical invariants.

In this chapter, we covered:

  • The Nature of Unsafe Rust: Its definition, the five operations it enables, and why Rust needs it.
  • Reasons for Unsafe Code: Hardware interaction, FFI, advanced data structures, and performance optimizations.
  • Unsafe Blocks and Functions: How to create them properly, including the requirement to call unsafe functions in unsafe blocks.
  • Raw Pointers: Their creation, dereferencing, pointer arithmetic, and how they differ from safe references.
  • Casting and transmute: How to reinterpret memory at a bit level, with an emphasis on the associated dangers.
  • Memory Handling: Interactions with RAII and the pitfalls of data races and invalid deallocations.
  • FFI: How to declare and call external C functions, and how to wrap them in safe functions.
  • Unions and Mutable Globals: Their uses, how they differ from typical variables, and their inherent dangers.
  • Unsafe Traits: Why some traits are unsafe and what it means to implement them.
  • Examples: Such as using unsafe pointer arithmetic to split a mutable slice.
  • Verification Tools: How to use Miri to detect undefined behavior in unsafe code.
  • Inline Assembly: Employing the asm! macro for direct CPU or hardware interactions.

25.14.1 Best Practices for Using Unsafe Code

  • Prefer Safe Rust: Rely on safe abstractions whenever possible.
  • Localize Unsafe Code: Confine unsafe operations to small blocks or modules that can be thoroughly reviewed.
  • Document Invariants: Make explicit the assumptions and requirements that the unsafe code depends on.
  • Review and Test: Use tools like Miri and perform rigorous code reviews.

25.14.2 Further Reading

  • The Rustonomicon for an in-depth exploration of advanced unsafe topics.
  • Rust Atomics and Locks by Mara Bos, a comprehensive low-level resource on concurrency.
  • Programming Rust by Jim Blandy, Jason Orendorff, and Leonora F.S. Tindall provides a detailed discussion of unsafe Rust with examples for its use.

Used judiciously, unsafe Rust offers the kind of low-level control found in C, while retaining Rust's safety benefits in the majority of your code.