19.5 Enums and Pattern Matching for Runtime Values

RUSTSTATUS: DEVELOPINGLEVEL: INTERMEDIATEREVIEWED: 2026-10-21
Before this page Ownership

19.5.1 Motivation

Every dynamic language must represent values at runtime. A vector, a number, a function, a list. These are all different types with different fields. C solves this with tagged unions: a header that says which type this is, plus type-specific data. R uses SEXPTYPE, a tag in each object’s header that identifies its type.

Rust has a better approach: enums. An enum is a type that can be one of several variants. Pattern matching is a control flow construct that checks which variant a value is and extracts its fields. The compiler enforces that all variants are handled. This is exhaustive checking.

19.5.2 The problem: representing dynamic values

In a statically-typed language like Rust, every value has a type known at compile time. An i32 is an integer. A String is text. The type system proves these facts and prevents type confusion.

But a dynamic language runtime must store many types in a single variable. An R variable can hold a vector, a list, a function, an environment. The runtime must know which type it is. This is the tagged union pattern.

In C, this means a struct with a tag field and a union of possible payloads. The code checks the tag and casts to the right type. A mistake in the cast is undefined behavior.

Rust enums make this safe. An enum value carries a tag and a payload. Pattern matching checks the tag and extracts the payload in one step. The compiler proves that all variants are handled.

19.5.3 Mental model: a single type with many shapes

An enum is a single type that can take many different forms. Here is a simple enum for R values:

enum Value {
    Integer(i32),
    Double(f64),
    List(Vec<Value>),
    Function(Box<dyn Fn(&[Value]) -> Value>),
}

A Value can be an integer, a double, a list, or a function. When you create a value, you choose which variant. When you use a value, you must check which variant it is.

The enum is type-safe. There is no cast. There is no confusion between variants. You cannot accidentally treat an integer as a function.

19.5.4 Mechanism: pattern matching

Pattern matching is the way to extract data from an enum. You match on the value and handle each variant separately.

match value {
    Value::Integer(i) => println!("integer: {}", i),
    Value::Double(d) => println!("double: {}", d),
    Value::List(items) => println!("list with {} items", items.len()),
    Value::Function(_) => println!("function"),
}

The match statement checks which variant the value is. For each variant, the code extracts the fields, and the compiler checks that every variant is handled. Forget a variant and the code does not build, which means adding a new value type to a runtime turns into a list of compile errors pointing at every place that has to learn about it. In contrast, C code using tagged unions often forgets to check the tag or handles only some cases. These bugs slip through to runtime.

19.5.5 Comparison with SEXPTYPE

GNU R uses a similar approach. Every SEXP header carries a type tag, read with TYPEOF. The code checks TYPEOF and then calls the accessor for that type.

if (TYPEOF(x) == VECSXP) {
    SEXP first = VECTOR_ELT(x, 0);
    // access list elements one at a time
} else if (TYPEOF(x) == INTSXP) {
    int* data = INTEGER(x);
    // access integer data
}

This pattern works but is error-prone. The C compiler sees only SEXP and cannot tell which cases a function forgot. The public accessors catch some mistakes at run time: INTEGER() applied to a double vector raises an R error. But that happens only when an input of the wrong type reaches the code, and a missing branch is caught by nothing at all.

Rust’s compiler tracks which variants have been handled in a match statement. If a variant is missing, the compilation fails.

match value {
    Value::Integer(i) => println!("i: {}", i),
    Value::Double(d) => println!("d: {}", d),
    Value::List(items) => println!("list"),
    // ERROR E0004: non-exhaustive patterns: `Value::Function(_)` not covered
}

Exhaustiveness checking is a form of proof, though a narrow one: the compiler proves that every variant has a branch, not that each branch is right. C code over SEXPTYPE gets no such check.

Like GNU R, r-in-rust represents matrices, data frames, and factors with attributes, not as separate enum variants. A matrix is an atomic or list vector with a dim attribute. A factor is an integer vector with levels and class attributes. A data frame is a list with a class attribute. This keeps the core value type small and leaves the rest to the attribute machinery.

19.5.6 Other systems

C uses tagged unions with explicit tag checking. The programmer is responsible for getting it right. GCC and Clang warn (-Wswitch) when a switch over an enum type misses a value, but R’s header declares SEXPTYPE as a plain unsigned int with #define constants, so even that warning does not apply to R code.

Python uses runtime type checking. isinstance() checks the type. If the check is missed, the program fails at run time with an exception such as TypeError.

Java uses inheritance and polymorphism. Each type is a class that inherits from a base class, and method dispatch finds the right implementation. Since Java 21, sealed interfaces combined with pattern matching for switch give an exhaustiveness check close to Rust’s.

Rust uses enums and pattern matching, and the compiler checks exhaustiveness at compile time.

19.5.7 Pattern matching in practice

The rrs value type is an enum, ObjKind, with a variant for each kind of R object. A match on it that lists every variant gets the compile errors described above when a variant is added; a _ arm opts out of that help, which is the trade-off the next examples show.

The most common mistake is to use if let instead of match and forget to handle other cases.

if let Value::Integer(i) = value {
    println!("integer: {}", i);
}
// What if value is a Double? Nothing happens.

if let only checks one variant. If the variant does not match, execution continues. The developer must remember to handle other cases elsewhere. This is error-prone. The compiler does not enforce exhaustiveness for if let. This is intentional: if let is for cases where only one variant matters. But if all cases matter, match is the right choice.

Pattern matching can be nested to inspect deep structures. This is useful for values that contain other values.

match value {
    Value::List(items) => {
        match items.first() {
            Some(Value::Integer(i)) => println!("first is int: {}", i),
            Some(Value::Double(d)) => println!("first is double: {}", d),
            None => println!("empty list"),
            _ => println!("other"),
        }
    }
    _ => {}
}

The nested match inspects the first element of a list. The compiler still enforces exhaustiveness. All cases must be handled. The if let syntax offers a shorthand for simple cases:

if let Value::List(items) = value {
    if let Some(Value::Integer(i)) = items.first() {
        println!("first is int: {}", i);
    }
}

This is clearer than nested matches when you only care about one branch. Another mistake is to panic on a variant that can really occur.

match value {
    Value::Integer(i) => println!("i: {}", i),
    _ => panic!("unexpected variant"),
}

The _ pattern matches anything. If an unexpected variant does occur, the program panics. This is fine for true invariants. But it is a code smell. If all variants are possible, handle them explicitly.

19.5.8 Option and Result types

Rust uses enums for two common patterns: optional values and error handling.

Option<T> is an enum with two variants: Some(T) and None. It represents a value that may be absent.

Result<T, E> is an enum with two variants: Ok(T) and Err(E). It represents a value that can be an error.

Pattern matching on these types is idiomatic:

match value {
    Some(x) => println!("value is {}", x),
    None => println!("no value"),
}

match result {
    Ok(x) => println!("success: {}", x),
    Err(e) => println!("error: {}", e),
}

These enums are so common that Rust provides shortcuts such as the ? operator for propagating errors. But the underlying mechanism is always pattern matching on enums.

For an R runtime, Result is the natural way to carry an R error out of a computation. Option is not used for NA, though. GNU R stores NA inside the vector as a sentinel value (INT_MIN for integers and logicals, a NaN with 1954 in its low word for doubles), and rrs uses the same bit patterns.

Further reading

Where this appears

  • r-in-rust (rrs) Values are represented as tagged enums. Pattern matching is exhaustive checking that all cases are handled.

Where to go next

Back to top