25.14 Summary and Further Resources

Unsafe Rust lets you step outside the boundaries of safe Rust, allowing low-level programming and direct hardware interaction. However, with this freedom comes responsibility: you must manually ensure memory safety, freedom from data races, and other crucial invariants.

In this chapter, we covered:

  • The Nature of Unsafe Rust: What it is, 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 correctly, including the need to call unsafe functions within unsafe blocks.
  • Raw Pointers: How to create and dereference them, plus pointer arithmetic.
  • Casting and transmute: Bitwise re-interpretation of memory and its inherent risks.
  • Memory Handling: How RAII still applies, and the pitfalls of data races and invalid deallocations.
  • FFI: Declaring and calling external C functions, and creating safe wrappers.
  • Unions and Mutable Globals: How they work, when to use them, and their dangers.
  • Unsafe Traits: Why certain traits are unsafe and what implementing them entails.
  • Examples: Using unsafe pointer arithmetic to split a mutable slice.
  • Verification Tools: Employing Miri to detect undefined behavior.
  • Inline Assembly: Using the asm! macro for direct CPU or hardware operations.

25.14.1 Best Practices for Using Unsafe Code

  • Prefer Safe Rust: Rely on safe abstractions whenever possible.
  • Localize Unsafe Code: Restrict unsafe operations to small, well-reviewed areas.
  • Document Invariants: Clearly outline the assumptions required for safety.
  • Review and Test: Use Miri, Valgrind, and thorough code reviews to catch memory errors.

25.14.2 Further Reading

  • Rustonomicon for a deep dive into advanced unsafe topics.
  • Rust Atomics and Locks by Mara Bos, an excellent low-level concurrency resource.
  • Programming Rust by Jim Blandy, Jason Orendorff, and Leonora F.S. Tindall, which provides detailed coverage of unsafe Rust usage.

When applied thoughtfully, unsafe Rust provides the low-level control found in languages like C while still preserving Rust’s safety advantages in most of your code.