skip to content

In Rust, how can one PaymentEvent enum hold unit, tuple and struct variants carrying different data, and how do you read it?

level: juniorimportance: must knowfreq 75%

answer

  1. one type, several shapes
  2. the variant name builds the value
  3. no field access on the enum
  4. match binds the present variant's fields

basics

~20 s

A Rust enum lists variants that may each carry their own fields: none (unit), positional (tuple) or named (struct). Every variant builds a value of the one enum type, and the fields are read only by matching the variant.

solid answer

~40 s

Each variant of `PaymentEvent` is a constructor: `Heartbeat` is a value, `Refunded(1_500)` is called like a function, and `Captured { amount_cents: 9_900, fee_cents: 300 }` is built like a struct. All three produce one type, `PaymentEvent`, so they share a `Vec`, a parameter and a return type. A value holds one variant's fields at a time, and rustc will not let you write `event.0` (E0609), because the type does not say which variant is there; you read the payload with a pattern, which binds the fields of the variant that is present. Behaviour goes in an ordinary `impl PaymentEvent` block, where a method such as `cents_moved(&self) -> Option<u64>` matches on `self` once for every caller. A variant is not a type of its own: `fn f(e: PaymentEvent::Refunded)` is E0573.

code

rust · 30 lines
rust
#[derive(Debug)]
enum PaymentEvent {
    Heartbeat,                                      // unit variant
    Refunded(u64),                                  // tuple variant
    Captured { amount_cents: u64, fee_cents: u64 }, // struct variant
}

impl PaymentEvent {
    fn cents_moved(&self) -> Option<u64> {
        match self {
            PaymentEvent::Heartbeat => None,
            PaymentEvent::Refunded(cents) => Some(*cents),
            PaymentEvent::Captured { amount_cents, fee_cents } => {
                Some(amount_cents - fee_cents)
            }
        }
    }
}

fn main() {
    let mut ledger = vec![
        PaymentEvent::Heartbeat,
        PaymentEvent::Captured { amount_cents: 9_900, fee_cents: 300 },
    ];
    // A tuple variant's name is also a constructor function.
    ledger.extend([250, 700].into_iter().map(PaymentEvent::Refunded));
    for event in &ledger {
        println!("{event:?} -> {:?}", event.cents_moved());
    }
}

go deeper

for a junior

Declare a unit, a tuple and a struct variant, build each one, and read the fields with a match arm that binds them.

for a middle

Explain that variant names are constructors in the value namespace, why event.0 is E0609 and a variant used as a type is E0573, and how one impl block serves every variant.

for a senior

Model a domain so that combinations which must not exist cannot be constructed, and keep the matching inside the enum's own methods so a new variant breaks one place, not every caller.

for a principal

Weigh a closed enum against a trait with several implementing types: the enum makes every case visible to the compiler, the trait lets other code add cases without touching yours.

## What a data-carrying enum is An **enum** in Rust declares one type together with a fixed list of **variants**, and each variant may carry its own fields. A value of the enum holds exactly one variant at a time, plus exactly that variant's fields. This is what makes Rust enums more than named integer constants: a `PaymentEvent` can be a bare heartbeat, a refund with an amount, or a capture with an amount and a fee, and all three are values of the same type `PaymentEvent`. Because they share one type, the variants travel together: - a `Vec<PaymentEvent>` can hold a heartbeat next to a refund next to a capture; - a function `fn record(event: PaymentEvent)` accepts any of them; - a method defined once on `PaymentEvent` is available on every value, whichever variant it holds. ## The three variant shapes | Shape | Declaration | Built with | Read with a pattern | |---|---|---|---| | unit | `Heartbeat` | `PaymentEvent::Heartbeat` | `PaymentEvent::Heartbeat` | | tuple | `Refunded(u64)` | `PaymentEvent::Refunded(1_500)` | `PaymentEvent::Refunded(cents)` | | struct | `Captured { amount_cents: u64, fee_cents: u64 }` | `PaymentEvent::Captured { amount_cents: 9_900, fee_cents: 300 }` | `PaymentEvent::Captured { amount_cents, fee_cents }` | The Reference states the rule behind the "built with" column: tuple-like and unit-like variants define a constructor in the **value namespace**. A unit variant is a constant value. A tuple variant's name is a function, so `[250, 700].into_iter().map(PaymentEvent::Refunded)` builds two refunds without a closure. A struct variant has no call form: `PaymentEvent::Captured(9_900, 300)` fails with E0533, "expected value, found struct variant", and you build it with braces and field names. ## Reading the payload: patterns, not field access The type `PaymentEvent` does not say which variant a value holds, so the compiler gives you no direct path to a field: - `event.0` on a `PaymentEvent` fails with **E0609**, "no field `0` on type `PaymentEvent`": the enum type has no fields, only its variants do. - A variant is not a type. Each variant defines a type name, but the Reference says that type "cannot be used as a type specifier", so `fn refund_amount(e: PaymentEvent::Refunded)` fails with **E0573**, "expected type, found variant". - You reach the fields with a **pattern**. A `match` arm such as `PaymentEvent::Refunded(cents) => ...` runs only for that variant and binds `cents` to its field; `if let` does the same for one variant (it belongs with the control-flow material). - `std::mem::discriminant(&event)` tells you which variant is present without the payload, as an opaque value you can compare or hash, not a number. The rules for which arms a `match` must contain, guards and the `_` wildcard belong with the material on match and exhaustiveness; here the point is that, in safe code, a pattern is the only door to the data. ## Methods on an enum An enum takes an ordinary inherent `impl` block, exactly like a struct. The usual shape of a method is a `match self` that answers for each variant: 1. Write `impl PaymentEvent { ... }` once, not once per variant (`impl PaymentEvent::Refunded` is E0573 again). 2. Take `&self` when the method only reads, `&mut self` when it may replace the value with another variant (`*self = PaymentEvent::Heartbeat;`), and `self` when it consumes the event. 3. Match on `self` and return a type that fits every variant. `cents_moved(&self) -> Option<u64>` returns `None` for a heartbeat, because a heartbeat moves no money. 4. Callers then ask `event.cents_moved()` and never repeat the match themselves. Putting the match in one method means that when a new variant is added, the compiler points at that one method rather than at every caller, as long as the method lists every variant instead of ending with a `_` arm. ## What an enum does not get for free A fresh enum has no operators and no printing. `event == PaymentEvent::Heartbeat` fails with **E0369**, "binary operation `==` cannot be applied to type `PaymentEvent`", until the type implements `PartialEq`; `{:?}` needs `Debug`. Both usually come from `#[derive(...)]`, which belongs with the standard traits. To test only which variant is present, `matches!(event, PaymentEvent::Heartbeat)` needs no derive at all. ## Why model it this way The alternative a reviewer sees is a struct with a `kind` field and a set of optional fields, where nothing stops a heartbeat from carrying a fee. With the enum, a heartbeat cannot be built with a fee: the shape of each variant is checked by rustc at every construction site. The general theory of such sum types has its own lesson; the Rust-specific gain is that the compiler enforces the shapes and that every read goes through a pattern.

  • Can you pass `PaymentEvent::Refunded` where a closure taking a `u64` and returning a `PaymentEvent` is expected?
    Yes. A tuple variant's name is also a constructor function, so `amounts.into_iter().map(PaymentEvent::Refunded)` works, and Clippy's `redundant_closure` lint suggests it over `|c| PaymentEvent::Refunded(c)`. A unit variant is a constant, not a function, and a struct variant has no call form at all: it is built with braces and field names.
  • Why does `if event == PaymentEvent::Heartbeat` fail to compile on this enum, and what is the lighter fix?
    An enum gets no operators by default, so `==` needs a `PartialEq` implementation and rustc reports E0369. Deriving `PartialEq` fixes it but also compares payloads. To ask only which variant is present, `matches!(event, PaymentEvent::Heartbeat)` works with no derive and ignores the fields.
  • Can a method change which variant a value holds?
    Yes, through `&mut self`: `*self = PaymentEvent::Heartbeat;` replaces the whole value with another variant. To keep the old one, `std::mem::replace(self, PaymentEvent::Heartbeat)` swaps in the new variant and returns the previous value, payload included.

  • You can read a tuple variant's field directly with event.0.
  • Each variant is its own type, so a function can take PaymentEvent::Refunded.
  • All variants of a Rust enum must carry the same set of fields.
  • Rust enums are only named integers; their data needs a separate struct.
  • An enum value stores the fields of every variant at once.