Enums
Simple and payload-carrying enum cases, with exhaustive pattern matching.
An enum is a sum type: exactly one of a fixed set of variants, optionally with data attached.
enum Status {
Pending
Active
Closed
}
fn describe(s: Status) -> string {
match (s) {
case Status.Pending -> { return "waiting" }
case Status.Active -> { return "running" }
case Status.Closed -> { return "done" }
}
}
fn main() {
println(describe(Status.Pending)) // waiting
println(describe(Status.Closed)) // done
}
Every variant must be handled
A match over an enum has to cover each variant, and each arm body must be a
block. There is no default and no bare case -> catch-all.
Variants with data declare named fields
If a variant carries values, the payload fields are named, in the declaration:
enum Shape {
Circle(r: float)
Rect(w: float, h: float)
Point2
}
fn area(s: Shape) -> float {
match (s) {
case Shape.Circle(r) -> { return 3.14159 * r * r }
case Shape.Rect(w, h) -> { return w * h }
case Shape.Point2 -> { return 0.0 }
}
}
fn main() {
println(area(Shape.Circle(2.0))) // 12.56636
println(area(Shape.Rect(3.0, 4.0))) // 12
println(area(Shape.Point2)) // 0
}
Two details are easy to get wrong, and both are hard errors:
- Write the payload names in the declaration:
Circle(r: float), notCircle(float). The bare form does not parse. - Refer to the variant fully qualified in the match:
case Shape.Circle(r), notcase Circle(r). An unqualified variant name is rejected as a pattern.
Building a variant
Construct a variant through the enum name, with the payload values in order:
enum Shape {
Circle(r: float)
Rect(w: float, h: float)
Point2
}
fn main() {
let c = Shape.Circle(1.5)
match (c) {
case Shape.Circle(r) -> { println("radius {r}") }
case _ -> { println("something else") }
}
}
Payload fields are not properties
c.r is not valid, there is no field access on a variant. Unwrap the variant
in a match:
enum Shape {
Circle(r: float)
Point2
}
fn radiusOf(s: Shape) -> float {
match (s) {
case Shape.Circle(r) -> { return r }
case _ -> { return 0.0 }
}
}
fn main() {
println(radiusOf(Shape.Circle(2.0))) // 2
}
if let does not unwrap an enum variant. It works on Option values only,
so if (let some(v) = shape) is a type error.
Enums as map keys
Enums work as map keys and as list elements, because the compiler knows how to name and order them:
enum Status {
Pending
Active
}
fn main() {
let counts: Map<Status, int> = {Status.Pending: 3, Status.Active: 1}
println(counts[Status.Pending]) // 3
println(len(counts)) // 2
}
Note that optionals are not enums in source. They are written T? and unwrapped
with if let. See Error handling.
