Lesson 5: Domain modeling with struct and enum

Model state with struct and enum, and demand coverage with match.

Goal

In one sentence: create composite data and destructure it exhaustively and safely.

Code

struct User {
    name: str
    balance: int
}

enum Account {
    Individual(User),
    Joint(User, User),
    Closed,
}

An enum with embedded data lets you represent variations cleanly. Let us destructure with match:

public func describe(account: ref Account): str {
    return match account {
        Account.Individual(u) => "Individual of " + u.name,
        Account.Joint(u1, u2) => "Joint of " + u1.name + " and " + u2.name,
        Account.Closed => "Closed",
    }
}

Try it

Remove the .Closed case from the match. The compiler flags the problem: the match does not cover all cases. Exhaustiveness guaranteed at compile time.

Guarantee

This is the compiler preventing a classic bug: adding a variant to an enum and forgetting to handle it somewhere. Without exhaustive match, this would go unnoticed.

With struct, enum, and match, you model complex domains and the compiler ensures nothing goes unhandled.

Next steps

You have seen the pillars. To consult types, operators, and the full grammar, see the reference.