Is 'unsafe' code a good thing?

Your experience of "When it finally compiles, it just works without problems and is (comparatively) easy to refactor should the need arise" is common among Rustaceans. Which brings us back to the subject of this thread: "Is unsafe code a good thing?"

For me that answer has multiple parts:

  1. unsafe code is necessary to implement many of the safe foundational abstractions that Rust offers within std and a few other crates. IMO this is a good thing.
  2. unsafe code is necessary to work at the bare-metal level in embedded systems or, for crypto, to avoid timing side-channels. IMO this also is a good thing.
  3. unsafe code is necessary to interface to all those other languages that are inherently unsafe (e.g., C, C++). IMO this is unavoidable; such interfaces are just an extension of the unsafety of those other languages.
  4. Judicious use of unsafe code is sometimes called for to improve critical "hot paths" in high-traffic or time-critical code. IMO this is unfortunate but understandable.
  5. unsafe code is often used in what amounts to premature optimization. IMO this is ill-advised and completely avoidable.
  6. unsafe code is often used in attempts to circumvent the borrow checker, often – though not always – resulting in UB. IMO this is [Edit: completely usually] avoidable.
11 Likes