Zeeshan Adil
Book a call
← Rust for C# Engineers: From Garbage Collection to Ownership and Lifetimes

Chapter 15 of 16 · Part IV, Under the hood

Unsafe is a smaller word than you think

by Zeeshan AdilUpdated 14 min read
Listen to this articleRust unsafe Explained for C# Engineers 16 min · read by an AI voice
0:00 / 15:30

The operations unsafe permits and the checks that still apply, why the boundary is the architecture, how it compares with C# unsafe code, and why you rarely need it.

This chapter assumes you understand ownership, borrowing, and slices. You will learn to identify the promise an unsafe operation requires and how a safe wrapper enforces it. Reading the boundary is useful even if you never need to write unsafe code yourself.

Every so often someone points out that Rust has unsafe, therefore the safety guarantees are theater. That argument does not survive contact with what the keyword actually does.

The familiar unsafe operations include:

  1. Dereference a raw pointer.
  2. Call an unsafe function, including foreign declarations that are unsafe to call.
  3. Access a mutable static or an unsafe external static.
  4. Read a union field, where the active value may not satisfy that field's type.
  5. Call a target-feature function when the caller does not establish the required CPU features.

Other uses mark declarations: unsafe impl for a trait, unsafe extern blocks, and unsafe attributes. Implementing an unsafe trait is a declaration-level promise, not a power granted by an unsafe block.

Note what is not on it. The borrow checker still runs. Types are still checked. Lifetimes are still enforced. Ownership still moves. Drop still runs. unsafe does not turn off the language, it permits particular operations whose safety conditions the compiler cannot establish.

You can watch it refuse things. The diagnostic is E0133, and it is worth seeing the exact wording, because the note at the bottom tells you what obligation you just picked up:

Code
error[E0133]: dereference of raw pointer is unsafe and requires unsafe function or block
 --> src/main.rs:2:13
  |
2 |     let _ = *p;
  |             ^^ dereference of raw pointer
  |
  = note: raw pointers may be null, dangling or unaligned; they can violate aliasing rules and cause data races: all of these are undefined behavior

The same code with a mutable static gets a different note:

Code
error[E0133]: use of mutable static is unsafe and requires unsafe function or block
  |
  = note: mutable statics can be mutated by multiple threads: aliasing violations or data races will cause undefined behavior

And calling an unsafe fn gets a third, which is the most instructive of the three: "consult the function's documentation for information on how to avoid undefined behavior". The compiler is not saying "this is dangerous". It is saying "somebody wrote down a condition, go read it, and then assert that you have met it".

The keyword is a proof obligation moving hands. That is genuinely all it is.

The boundary is the architecture

The part that takes longest to appreciate: unsafe is not primarily an escape hatch for application code. It is how the standard library is built.

Vec<T> is unsafe inside. Since push_mut stabilized in Rust 1.95, Vec::push is a one-line wrapper that calls it and discards the reference, so the body worth reading is push_mut:

Code
pub fn push_mut(&mut self, value: T) -> &mut T {
    // Inform codegen that the length does not change across grow_one().
    let len = self.len;
    // This will panic or abort if we would allocate > isize::MAX bytes
    // or if the length increment would overflow for zero-sized types.
    if len == self.buf.capacity() {
        self.buf.grow_one();
    }
    unsafe {
        let end = self.as_mut_ptr().add(len);
        ptr::write(end, value);
        self.len = len + 1;
        // SAFETY: We just wrote a value to the pointer that will live
        // the lifetime of the reference.
        &mut *end
    }
}

Look at what is going on. Pointer arithmetic with add. A write into memory that is uninitialized, using ptr::write specifically because assignment would try to drop whatever garbage was already there. A length field updated by hand afterward. Every one of those steps is undefined behavior if the capacity check above it is wrong.

And the signature is completely safe. There is no way to call push incorrectly, no way to observe the uninitialized region, no way to get the length out of step with the initialized prefix, because len and buf are private and every method that touches them maintains the same invariant.

RefCell is unsafe inside. Arc is unsafe inside, including the memory ordering on its counter. Mutex uses a platform-specific locking implementation; its representation is not a portable API guarantee. Every one of them exposes a safe API.

You can write the same shape yourself in a few lines. This is a complete program:

Code
use std::slice;

fn split_at_mut<T>(values: &mut [T], mid: usize) -> (&mut [T], &mut [T]) {
    let len = values.len();
    let ptr = values.as_mut_ptr();

    assert!(mid <= len);

    // SAFETY: `mid <= len` was just checked, so both ranges are inside the
    // same allocation. The two ranges do not overlap, so handing out two
    // mutable slices does not alias.
    unsafe {
        (
            slice::from_raw_parts_mut(ptr, mid),
            slice::from_raw_parts_mut(ptr.add(mid), len - mid),
        )
    }
}

fn main() {
    let mut v = vec![1, 2, 3, 4, 5, 6];
    let (left, right) = split_at_mut(&mut v, 3);

    left[0] = 100;
    right[0] = 200;
    println!("{left:?} {right:?}");

    println!("{v:?}");
}

Two mutable slices into disjoint regions are valid. This wrapper supplies the proof that its raw-pointer construction preserves that disjointness. It is sound anyway, because the assertion plus the arithmetic proves the two ranges are disjoint, and that proof is written down in the comment above the block. The function's callers get an ordinary safe API and never see any of it.

That is the actual architecture: a large safe language sitting on a small unsafe core, with the boundaries explicit and greppable. Compare it to C or C++, where every line has the same authority as every other, and auditing means reading all of it.

The greppable part is not rhetorical. Put #![forbid(unsafe_code)] at the top of a crate and the compiler will reject any unsafe block in it, along with no_mangle, export_name and link_section, which turns "we do not write unsafe code here" from a code review convention into a build failure. It is a crate-level lint, so it says nothing about your dependencies.

The compiler pushes from the other side too. Wrap something safe in an unsafe block and the unused_unsafe lint fires:

Code
warning: unnecessary `unsafe` block

That keeps the marked regions honest as the code underneath them changes.

If you do write it, Miri is the tool. cargo miri test runs your test suite under an interpreter that detects out-of-bounds access and use-after-free, invalid use of uninitialized data, insufficiently aligned accesses, values that violate their type's invariants such as a bool that is not 0 or 1, data races, and, as an experimental feature, violations of the Stacked Borrows or Tree Borrows aliasing rules. Interpretation costs what interpretation costs, and Miri only sees the paths your tests actually execute, and it is still the best thing available by a distance. If a crate of yours has an unsafe core, running Miri over its tests in CI is the single highest-value thing you can do.

The C# comparison, which is closer than you expect

C# has all of this, in pieces, with different names.

unsafe plus AllowUnsafeBlocks gives you raw pointer types and pointer arithmetic. fixed pins a managed object so the collector cannot move it while you hold a pointer into it, which addresses relocation by the GC. Rust has no moving GC, but ordinary moves and container reallocation can still change addresses; references, allocation choices, and Pin address those cases. stackalloc allocates a block in the stack frame. Marshal does manual allocation, copying and layout work across the native boundary. And System.Runtime.CompilerServices.Unsafe is the genuinely sharp one: Unsafe.As reinterprets a reference as a reference to another type with no check at all, which is the same move as a std::mem::transmute between reference types and just as capable of producing a value that cannot exist.

Same shape as Rust, then: a small marked door out of the safe language, for the cases the safe language cannot express.

Three differences matter.

Scope. C# requires an unsafe context for pointer operations and certain other constructs, enabled by AllowUnsafeBlocks. Some related tools, such as stackalloc into a Span<T>, are usable in safe code. Rust marks specific operations and declarations. In both languages, review the actual contract at each boundary.

Ecosystem convention. In Rust, the safe wrapper around an unsafe core is the expected design, the community reviews crates on that basis, and forbid(unsafe_code) is a badge people put in readmes. In .NET the same discipline exists in the runtime itself and much less consistently outside it, partly because there is far less need for it.

Tooling. There is no Miri for .NET. There is also much less demand for one, and that is the honest reason.

Where C# is genuinely better here

You will almost never need any of it.

That is not a small thing. The reason Rust needs a carefully specified unsafe subset with a dedicated interpreter to check it is that Rust has to build Vec out of raw memory. In C#, the collector already solved the lifetime problem, List<T> already exists, and Span<T> covers the large majority of what raw pointers used to be for while staying inside the safe, bounds-checked, GC-tracked world. A .NET engineer can have a long and productive career without writing unsafe once, and that is a genuine advantage of the platform rather than a gap.

.NET's native interop story is also more mature and much better documented as a product. P/Invoke has been in the platform for two decades, the marshalling rules are specified, the LibraryImport source generator produces readable code you can step through, and the guidance is thorough. Rust's FFI is more primitive by design: you get extern "C", raw pointers, and a lot of hand-written glue, or you reach for a crate that generates the glue.

The mistakes a C# engineer makes with unsafe

Wrapping a borrow error in unsafe to make it go away. This is the reflex, and it does not work. unsafe does not disable the borrow checker, so the error you were fighting is unchanged and you have added a marker that lies about what the code needs. If E0499 or E0502 is what you are seeing, unsafe is not the fix and there is no version of this where it becomes the fix.

Treating unsafe fn as "this function is dangerous". It means "this function has preconditions the compiler cannot check, and the caller must satisfy them". Marking a function unsafe because it does something you find scary, when it has no preconditions, is noise. Marking it safe when it does have preconditions is a bug, and it is the specific bug that makes a crate unsound.

Not writing the safety comment. Every unsafe block should be preceded by a comment naming the invariant that makes it sound, in the style the standard library uses. If you cannot write the sentence, you do not have the proof, and the block should not be there. This is the most valuable habit in the whole subject and it costs nothing.

Reaching for static mut. The direct translation of a C# static field, and in edition 2024 taking a reference to one is an error rather than a warning. What you want is OnceLock for initialize-once, an atomic for a counter, or a Mutex for anything else.

Assuming unsafe means C-like performance. It does not make anything faster on its own. get_unchecked removes a branch the predictor was almost certainly getting right; where it occasionally earns its keep is when the check was the thing stopping a loop from vectorizing. Measure first, and expect the answer to be that the bounds check was not your problem.

You probably will not write it

Realistically, in your first year you will write unsafe if you are doing foreign function interface work, implementing a data structure the borrow checker genuinely cannot express, or chasing a specific performance problem you have already measured. Those are real reasons and there is nothing wrong with any of them.

The rest of the time you will use it constantly without noticing, because it is underneath every Vec, every String, every Mutex, every channel and every allocation you make. Somebody already wrote the proof, wrote it down next to the code, and put a safe type around it. That arrangement, not the keyword, is the thing worth taking away.

Checking yourself

What does "zero cost" actually claim, and what does it not claim? It claims that the abstraction adds nothing over the code you would have written by hand, and that features you do not use cost you nothing. It does not claim the operation is free, that Rust is faster than C#, or that the compiler always succeeds.

A colleague says Rust bounds checks make it slower than C#. What is wrong with that? Both languages bounds check by default and both eliminate the check when they can prove the index is in range, with the same iterate-rather-than-index pattern making it provable in both. It is not a difference between the languages.

Does an unsafe block let you ignore the borrow checker? No. It enables specific unsafe operations, such as dereferencing raw pointers and calling unsafe functions. Ordinary borrow and type checking still apply. An unsafe block does not make conflicting references valid.

Why is Vec::push safe to call when its body does pointer arithmetic into uninitialized memory? Because the unsafe operations sit behind an invariant the type enforces privately: the capacity check happens before the write, and len and the buffer are inaccessible from outside. The safe API is the boundary, and the proof that the boundary holds is written down next to the code.

Get the next deep dive by email

New deep dives on how production systems really behave, from Kubernetes networking to PostgreSQL internals. About one email a month.

You will get one email to confirm. Unsubscribe from any email with one click. Your address is used for this newsletter and nothing else.

Written by Zeeshan Adil

I run systems like this for a living. If your team is fighting the same problem, or wants this as a talk, write to me.