8. Enums and match
An enum is a type whose value is one of a fixed set of variants, each of which can carry its own data. Together with match, enums replace several features from other languages: constants, None/null, exceptions for expected failures, and class hierarchies. This chapter shows how to define enums, take them apart with match, and use match on plain numbers and strings.
A simple enum
The simplest enum is a list of names:
enum Suit:
Hearts
Diamonds
Clubs
Spades
fn is_red(s: Suit) bool:
return s == Suit.Hearts or s == Suit.Diamonds
fn main():
hand = [Suit.Spades, Suit.Hearts, Suit.Clubs]
for s in hand:
print(s, is_red(s))Suit.Spades false
Suit.Hearts true
Suit.Clubs falseYou write a variant as Enum.Variant. Variants without data can be compared with == and !=, and they print as Suit.Hearts.
Compared with using strings ("hearts") or numbers (1), an enum can't be misspelled and can't hold a value outside the set, and the compiler can check that you handled every case.
match
match picks a block by the variant of a value. Each arm names a variant and has its own block; there is no fallthrough and no case keyword:
enum Light:
Red
Yellow
Green
fn after(l: Light) Light:
match l:
Red:
return Light.Green
Green:
return Light.Yellow
Yellow:
return Light.Red
fn main():
l = Light.Red
for i in 0..4:
print(l)
l = after(l)Light.Red
Light.Green
Light.Yellow
Light.RedIn a pattern you can write the bare variant name (Red) or the full one (Light.Red).
A match on an enum must handle every variant. If you forget one, the compiler lists what is missing. That is what makes enums safe to extend: add a variant, and the compiler shows you every match that needs updating.
enum Light:
Red
Yellow
Green
fn after(l: Light) Light:
match l:
Red:
return Light.Green
Green:
return Light.Yellow
fn main():
print(after(Light.Red))6: error: function `after` must end with a `return`
7: error: match on Light doesn't handle Yellow (add them, or a `_:` arm)When you really do want to treat the rest alike, end with a _: arm, which matches anything.
Variants that carry data
Each variant can have its own fields, written like function parameters. match binds them to names, by position:
import math
enum Shape:
Circle(radius: float)
Rect(w: float, h: float)
Point
fn area(s: Shape) float:
match s:
Circle(r):
return math.pi() * r * r
Rect(w, h):
return w * h
Point:
return 0.0
fn describe(s: Shape) str:
match s:
Rect(w, _):
return f"a rectangle {w} wide"
_:
return "not a rectangle"
fn main():
shapes = [Shape.Circle(1.0), Shape.Rect(w=2.0, h=3.0), Shape.Point]
for s in shapes:
print(area(s), describe(s))
print(shapes[1])3.141592653589793 not a rectangle
6.0 a rectangle 2.0 wide
0.0 not a rectangle
Shape.Rect(w: 2.0, h: 3.0)- Build a variant like a struct:
Shape.Circle(1.0)or with names,Shape.Rect(w=2.0, h=3.0). - In a pattern,
_skips a value you don't need (Rect(w, _)). - The names in the pattern are yours to choose:
Circle(r)binds the radius tor.
The data inside a variant can only be read with match, never with a dot. That is the point: a Shape might not be a circle, so s.radius would be a bug waiting to happen. == compares the variant and then its values:
enum Shape:
Circle(radius: float)
Square(side: float)
fn main():
s = Shape.Circle(1.0)
print(s.radius)7: error: Shape is an enum: use `match` to get at its valuesenum Shape:
Circle(radius: float)
Square(side: float)
fn main():
s = Shape.Circle(1.0)
print(s == Shape.Circle(1.0), s == Shape.Square(1.0))true false"Maybe" values without null
Tern has no null. When a result may be missing, say so with an enum. The caller then has to handle the missing case, because match must be complete:
struct User:
id: int
name: str
enum Lookup:
Found(u: User)
Missing
fn find_user(users: [User], id: int) Lookup:
for u in users:
if u.id == id:
return Lookup.Found(u)
return Lookup.Missing
fn main():
users = [User(1, "ada"), User(2, "grace")]
for id in [2, 7]:
match find_user(users, id):
Found(u):
print("found", u.name)
Missing:
print("no user", id)found grace
no user 7This shape is so common that two generic enums are built in. Option[T] is Some(value) or None; Result[T, E] is Ok(value) or Err(error), for operations that can fail with a reason. x is Pattern tests one variant and, in an if or while condition, names its values; x? gives the value inside Some/Ok, or returns the None/Err from the function right away:
struct User:
id: int
name: str
fn find_user(users: [User], id: int) Option[User]:
for u in users:
if u.id == id:
return Some(u)
return None
fn name_of(users: [User], id: int) Option[str]:
u = find_user(users, id)? # None: name_of returns None here
return Some(u.name.upper())
fn main():
users = [User(1, "ada"), User(2, "grace")]
if find_user(users, 1) is Some(u):
print("found", u.name)
print(name_of(users, 2), name_of(users, 7), name_of(users, 7).unwrap_or("?"))found ada
Some("GRACE") None ?Recursive enums
A variant can hold values of its own enum, which makes trees easy. Here is a tiny calculator:
enum Expr:
Num(v: int)
Add(l: Expr, r: Expr)
Mul(l: Expr, r: Expr)
fn eval(e: Expr) int:
match e:
Num(v):
return v
Add(l, r):
return eval(l) + eval(r)
Mul(l, r):
return eval(l) * eval(r)
fn show(e: Expr) str:
match e:
Num(v):
return str(v)
Add(l, r):
return "(" + show(l) + " + " + show(r) + ")"
Mul(l, r):
return show(l) + " * " + show(r)
fn main():
e = Expr.Mul(Expr.Num(2), Expr.Add(Expr.Num(3), Expr.Num(4)))
print(show(e), "=", eval(e))2 * (3 + 4) = 14match on numbers, strings, and bools
match also works on int, str, and bool values, with literal patterns. Like a match on an enum, it must handle every value, so it needs a _: arm for "anything else" (a bool match can list true and false instead). Write _: pass when the rest needs nothing:
fn status_text(code: int) str:
match code:
200:
return "OK"
404:
return "Not Found"
500:
return "Internal Server Error"
_:
return "Unknown"
fn main():
for code in [200, 404, 418]:
print(code, status_text(code))
for cmd in ["go", "look", "dance"]:
match cmd:
"go":
print("you walk north")
"look":
print("you see a door")
_:
pass200 OK
404 Not Found
418 Unknown
you walk north
you see a doorThere are no guards (Circle(r) if r > 1); put an if inside the arm instead. There is no switch: match is the only multi-way branch besides if/elif.
Try it
Model a vending machine's state as an enum: Idle, HasMoney(cents: int), and Dispensing(item: str). Write fn step(s: State, coin: int) State that moves from Idle to HasMoney when a coin arrives, adds coins while in HasMoney, and switches to Dispensing("soda") once 150 cents or more have been put in; from Dispensing it goes back to Idle. Feed it the coins [100, 25, 25, 0, 50] and print each state.
Solution
enum State:
Idle
HasMoney(cents: int)
Dispensing(item: str)
fn step(s: State, coin: int) State:
match s:
Idle:
if coin > 0:
return State.HasMoney(coin)
return State.Idle
HasMoney(c):
if c + coin >= 150:
return State.Dispensing("soda")
return State.HasMoney(c + coin)
Dispensing(_):
return State.Idle
fn main():
s = State.Idle
for coin in [100, 25, 25, 0, 50]:
s = step(s, coin)
print(coin, s)100 State.HasMoney(cents: 100)
25 State.HasMoney(cents: 125)
25 State.Dispensing(item: "soda")
0 State.Idle
50 State.HasMoney(cents: 50)Next: 9. Values, mut, and &. Reference: §9 Enums and match.