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

Chapter 10 of 16 · Part II, Working knowledge

The null that is not there

by Zeeshan AdilUpdated 13 min read
Listen to this articleRust Option vs C# Null and Nullable Reference Types 15 min · read by an AI voice
0:00 / 14:36

How Option<T> represents missing values and compares with C# nullable reference types, how to use it without drowning in match, converting to Result, and its runtime cost.

This chapter builds on enums and Result. Your goal is to distinguish an absent value from a failed operation, then choose an explicit default or error. Start with the lookup examples; the layout discussion is optional for everyday use.

Option<T> is the other enum you will use constantly, and it is built from the same parts:

Code
enum Option<T> {
    Some(T),
    None,
}

Rust references cannot be null. Optional values normally use Option<T>, which requires you to handle absence before accessing the payload. Raw pointers can still be null, even when created in safe code; dereferencing them requires an unsafe operation.

Code
fn find_server(id: u32) -> Option<Server> { /* ... */ }

match find_server(7) {
    Some(server) => println!("{}", server.hostname),
    None => println!("not found"),
}

The honest comparison with nullable reference types

C# 8 added nullable reference types, and it is a genuine improvement. It is also a different kind of thing, and the difference is worth being precise about because the marketing blurs it.

Nullable annotations are static analysis over a runtime that still has null. Microsoft's own documentation says it directly: the annotation does not change the runtime type, and string and string? are both System.String. The CLR does not check anything. The annotations live in metadata so that the compiler can read them across assemblies, which is why the feature works at all across NuGet packages, but nothing enforces them when the code runs.

The docs name two holes themselves, under "Known pitfalls", and call them limitations of the static analysis rather than bugs in your code:

Code
public struct Student
{
    public string FirstName;
    public string? MiddleName;
    public string LastName;
}

public static class Pitfalls
{
    public static void Show()
    {
        Student s = default;              // no warning, FirstName and LastName are null
        string[] values = new string[3];  // no warning, every element is null

        Console.WriteLine(s.FirstName is null);   // True
        Console.WriteLine(values[0] is null);     // True
    }
}

That builds with zero warnings on .NET 9 with nullable fully enabled, and prints True twice. Two fields and three array slots, all typed non-nullable, all holding null, and the compiler had nothing to say. There is no equivalent in Rust, because there is no way to conjure a String out of zeroes: vec![String::new(); 3] needs a real value to clone, and a struct with a String field cannot be produced without one.

Three more differences that matter day to day. Warnings are warnings, so a codebase can ship with hundreds of them. The null-forgiving ! operator silences any of them with one character and no justification required. And the analysis does not trace into method bodies, so a helper that checks for null teaches the compiler nothing unless you annotate it with [NotNullWhen] or a sibling from the nullable analysis attributes.

In Rust none of that applies, because Option<T> is a type rather than an annotation. match exhaustiveness is a compile error, not a warning. There is no !. There is no unannotated third-party crate whose optionality is unknown.

Where C# is genuinely ahead: nullable reference types were retrofitted onto twenty years of existing code, incrementally, file by file, with a per-project or per-file switch. Rust could never have done that, and if it had needed to, Option would not exist. Nullable<T> for value types has been sound since C# 2.0 and needs no defense at all. And for deep member access, a?.b?.c ?? d really is nicer than the equivalent chain of and_then calls. Language-level syntax beats combinators when the shape is common enough to deserve syntax.

Working with it without drowning in match

if let handles the one-case version:

Code
if let Some(server) = find_server(7) {
    println!("{}", server.hostname);
}

let else handles the early-return version, which is the shape most guard clauses want:

Code
let Some(server) = find_server(7) else {
    return Err(ConfigError::Missing { key: "server" });
};
// server is a plain Server from here on

The else block must leave that path with return, break, continue, or a panic. If execution reaches the comment, server is available as a plain value. Older code often uses a match for the same job.

You can also chain let bindings with && and use earlier bindings later in the condition. This next form requires Rust 1.88 or later and the Rust 2024 edition:

Code
if let Some(server) = find_server(7)
    && let Some(tls) = server.tls_config()
    && tls.is_valid()
{
    // ...
}

And there is a combinator for almost anything you would otherwise write by hand:

Code
let port = find_server(7)
    .map(|s| s.port)             // Option<Server> to Option<u16>
    .unwrap_or(5432);            // default if None

let name = find_server(7)
    .filter(|s| s.is_healthy())  // Some only if the predicate holds
    .map(|s| s.hostname)
    .unwrap_or_else(|| expensive_default());   // closure runs only on None

let region = find_server(7)
    .and_then(|s| s.region)      // map would give Option<Option<Region>>; this does not
    .unwrap_or_default();        // Default::default() on None

The mapping to LINQ is close enough to be useful: map is Select, and_then is SelectMany, filter is Where, unwrap_or is FirstOrDefault with a supplied default. The difference is that these are ordinary inherent methods on an ordinary enum rather than extension methods over IEnumerable, so there is no sequence and no deferred execution underneath, and Result has many analogous combinators, though its method set is not identical. Prefer unwrap_or_else over unwrap_or when the default costs anything, because unwrap_or evaluates its argument eagerly. Clippy has a lint for the case where it matters, or_fun_call, which fires when you pass a function call to unwrap_or instead of deferring it.

Converting between Option and Result

The two types are the same shape with different meaning, so the conversions are cheap and you will use them constantly.

Code
let server = find_server(7)
    .ok_or(ConfigError::Missing { key: "server" })?;   // Option to Result, then propagate

let server = find_server(7)
    .ok_or_else(|| ConfigError::Missing { key: "server" })?;  // lazy variant

let maybe: Option<Settings> = load_settings("app.toml").ok();   // Result to Option, discard why

let flipped: Result<Option<u16>, ParseIntError> =
    maybe_port_text.map(|t| t.parse::<u16>()).transpose();      // Option<Result> to Result<Option>

The last line uses transpose to keep two questions separate: was a port supplied, and was it valid?

maybe_port_textResult after parsing and transpose()Meaning
NoneOk(None)No port was supplied.
Some("5432")Ok(Some(5432))A valid port was supplied.
Some("eighty")Err(ParseIntError)A value was supplied, but parsing failed.

Turning the parse result into .ok() too early would erase that last distinction. A missing optional setting and a misspelled setting often deserve different responses.

? works on Option too, but only inside a function that itself returns Option. Use it in a Result-returning function and the compiler tells you precisely what to do:

Code
error[E0277]: the `?` operator can only be used on `Result`s, not `Option`s, in a function that returns `Result`
  --> src/config.rs:31:41
   |
28 | fn parse_port(raw: &str) -> Result<u16, ConfigError> {
   | -------------------------------------------------- this function returns a `Result`
...
31 |     let (_, value) = raw.split_once('=')?;
   |                                         ^ use `.ok_or(...)?` to provide an error compatible with `Result<u16, ConfigError>`

The label is the fix. This is not the generic trait error dressed up: the wording is a hand-written special case in core, attached to FromResidual with rustc_on_unimplemented, with its own message and its own suggested label for each direction of the mistake. Somebody decided this confusion was worth its own paragraph. The underlying error is the same one a C# habit produces: you reached for the propagation operator on a lookup that has no reason attached, and the type system is asking you to supply the reason.

It costs nothing, and that is mostly not a figure of speech

The obvious worry is that wrapping every optional value in an enum adds a tag byte and a branch.

The simplified model is that Option<T> is a tag plus a payload, sized to hold the larger case and aligned. That model is correct for Option<i32>: i32 has alignment 4 and every 32-bit pattern is a legitimate integer, so the tag needs its own space and alignment rounds the total to 8 bytes. Twice the size for the same number. That is the honest answer for plain integers.

For pointer-like types the model is wrong, and deliberately so. The compiler uses an invalid bit pattern inside the payload as the None marker. A Box, a &T, a NonNull and a function pointer can never be null, so null is free to mean None. This is the null pointer optimization, and the exact guarantee is written down in the standard library. Rust guarantees that Option<T> has the same size, alignment and function-call ABI as T for this list:

  • Box<U> where U: Sized, specifically only Box<U, Global>
  • &U and &mut U where U: Sized
  • fn and extern "C" fn
  • num::NonZero types
  • ptr::NonNull<U> where U: Sized
  • a #[repr(transparent)] struct wrapping any of the above

For those, transmuting a T into Option<T> is defined behavior, and for the cases the docs mark, an all-zero byte pattern is None. That is what makes Option<Box<T>> usable directly as a nullable pointer across an FFI boundary with no wrapper.

You can watch it yourself:

Code
use std::mem::size_of;

fn main() {
    println!("i32                {}", size_of::<i32>());
    println!("Option<i32>        {}", size_of::<Option<i32>>());
    println!("Box<i32>           {}", size_of::<Box<i32>>());
    println!("Option<Box<i32>>   {}", size_of::<Option<Box<i32>>>());
    println!("&i32               {}", size_of::<&i32>());
    println!("Option<&i32>       {}", size_of::<Option<&i32>>());
    println!("String             {}", size_of::<String>());
    println!("Option<String>     {}", size_of::<Option<String>>());
}

On a 64-bit target the pointer-shaped rows come out equal on both sides, and only Option<i32> is larger than the thing it wraps. String is three words, a pointer plus a length plus a capacity, and its pointer is non-null, so Option<String> is also three words. Amos has a byte-level walkthrough with the disassembly if you want to see the generated code rather than the sizes.

The branch is the other half of the worry, and it is the same branch you were already writing. Option<Box<T>> compiles to a null check. You wrote that null check by hand in C#, or the JIT inserted it for you and then usually elided it. The difference is not the instruction. It is that the compiler knows the check happened.

Option or Result

Use Option when absence is normal and carries no explanation. A cache lookup missed. A list was empty. A configuration key was not set and has a default. Nobody needs to know why, because there is no why.

Use Result when absence is a failure with a reason worth propagating. The file did not open, and the caller should know whether that was permissions or a missing path.

A workable test: if the caller might reasonably want to log or branch on the reason, it is a Result. If the only sensible response to None is a default or a different code path, it is an Option.

Reaching for Option where the caller will immediately want to know what went wrong is the most common design mistake here. ok_or exists precisely because people notice it one layer too late, and it is a cheap fix at the boundary. The reverse mistake, a Result whose error type carries no information anyone will read, is rarer but worse. Result<T, ()> is an Option with extra typing. Clippy's result_unit_err fires on public functions that return it and tells you to define a real error type.

Twenty modules in, the shape you converge on

A larger service often uses several layers of error types. Leaf modules expose specific failures; outer modules wrap or translate them; the HTTP boundary maps errors to responses. Exhaustiveness checking applies to the variants actually matched. Adding a nested error does not force a new HTTP decision if an outer arm already handles that whole category. That mapping still needs deliberate review.

The place it gets expensive is the mid-layer wrapping. Ten modules deep, you are writing conversions that only exist to move a value from one enum to another. Boxing into anyhow earlier removes the boilerplate and removes the exhaustive match at the top with it. That is a real trade and reasonable people land in different places. The defensible default: keep typed errors wherever a caller branches on the reason, and box everywhere else.

On the Option side, the scale effect is quieter and mostly about deserialization. Once every optional field in a config struct is an Option<T>, you get a struct where half the fields are optional and the code downstream is a forest of unwrap_or. The fix is the same one you would apply in C#: parse into a permissive shape once, validate into a strict shape with no optionals, and let everything after that point be total. Rust just makes the boundary between the two shapes visible in the type, which means the day someone adds a field they have to say which side of the boundary it lives on.

Checking yourself

Why does ? need a From implementation, and what does it call it on? ? on an Err returns Err(From::from(e)), converting the inner error type into the function's declared error type. Without a From implementation from the source error to your error, the conversion has nothing to call, and you get E0277, reported as the ? operator failing to convert the error to your declared type.

A function returns Option<Config> and callers keep asking why it was None. What changed, and what is the fix? Absence stopped being uninteresting and became a failure with a reason. Change the return type to Result<Config, E> with an enum naming the reasons, or convert at the boundary with ok_or if the inner function genuinely has no more information.

Your crate compiles with panic = "abort" in the release profile. Name two things that behave differently. Destructors no longer run during a panic, so anything relying on Drop for cleanup or flushing on the failure path silently stops happening, and catch_unwind can no longer recover. Binaries also get smaller because the landing pad code is not emitted.

Is Option<u64> the same size as u64, and why does the answer differ for Option<Box<u64>>? No. u64 has no unused bit pattern to represent absence, so Option<u64> needs extra storage; 16 bytes is a common measured layout, not a portable guarantee. For U: Sized, the standard library guarantees that Option<Box<U>> with the global allocator has the same size, alignment, and calling ABI as Box<U>, using the null representation for None.

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.