41 Nested patterns
A pattern may match a variant inside another variant's payload.
norm
enum Delivery {
Pending,
Sent(String code)
}
enum Event {
Updated(Delivery delivery),
Ignored
}
String describe(Event event) {
return switch event {
case Updated(Sent(String code)) { break code }
case Updated(_) { break "waiting" }
case Ignored { break "ignored" }
}
}
main() {
printLine(describe(event: Event.Updated(delivery: Delivery.Sent(code: "N-42"))))
printLine(describe(event: Event.Updated(delivery: Delivery.Pending)))
}Expected output:
text
N-42
waitingThe first case extracts the code only when an Updated event contains Sent. The next case handles other Updated deliveries; the final case handles Ignored. Cases are tested in order without falling through.
Try it: Swap the first two cases and observe whether the compiler flags an unreachable case.
Precise rules: Reference.