Match

2 Posts

match and Pattern Matching in Depth

6 minute

C programmers often first read match as a stricter switch.

That comparison helps at the beginning, but it is incomplete. C switch mainly branches on integer values. If the state also carries data, you still manually read fields from a struct or union.

Rust match performs pattern matching:

check what shape a value has, and bind the data inside that shape.

Earlier, when discussing enum, we used Rust enums as a safer replacement for C tagged unions. This article continues from there: how match handles richer state, references, conditions, and local unpacking.

Read More

Enums and Unions

5 minute

In C, enum and union often appear together. The enum says which kind of value is active, and the union reuses the same storage for different payloads:

enum ValueKind {
    VALUE_INT,
    VALUE_FLOAT,
    VALUE_TEXT,
};

struct Value {
    enum ValueKind kind;
    union {
        int i;
        float f;
        const char *text;
    } data;
};

This is a tagged union. It is common and useful, but correctness depends on discipline:

if (value->kind == VALUE_INT) {
    printf("%d\n", value->data.i);
}

If kind is VALUE_TEXT and the code reads data.i, the C type system does not stop it. In Rust, this shape is usually represented with enum, where the tag and the data live in one type.

Read More