About Unsafe Operation

The Rust compiler categorizes “unsafe Rust” into 13 different operations via UnsafeOpKind, but the Rust documentation only introduces five “unsafe superpowers” and says:

“The unsafe keyword only gives you access to these five features that are then not checked by the compiler for memory safety.”

How should this be understood?

1 Like

Some of those operations are newer than the book and the book could use updating to acknowledge them (like inline assembly). Some are still unstable (like unsafe fields) — they aren’t properly part of the language yet.

3 Likes

Can you please give us a link where these 13 different operations are listed?

I can find only these 5 mentioned everywhere as in

What Unsafe Can Do - The Rustonomicon

Presumably this rustc internal enum: UnsafeOpKind in rustc_mir_build::check_unsafety - Rust

Most are reasonably obvious from the name, the main ones I'm not sure about are:

  • InitializingTypeWith
  • Mutation/BorrowOfLayoutConstrainedField
  • UnsafeBinderCast

Presumably knowing more about compiler internals would make the latter two points a bit more obvious.

1 Like

Here's the unsafe binder tracking issue.

Based on an old PR,[1] InitializingTypeWith would be something like assigning null to a NonNull, and similarly for the constrained fields -- like, imagine the u8 of a NonZeroU8 was a public field and you tried to ref mut bind it in a pattern. At a guess, such things aren't exposed on stable Rust so far?


  1. the text has since moved elsewhere, for translation purposes perhaps ↩︎

2 Likes

...and probably will never be, since once we have pattern types there won't be this "I look like I'm a u32 but I'm really not" problem any more.

1 Like