Pattern matching#
match handles each case of an enum type and names the case’s data. Use it for your own enums and interface values. For Optionals and Results, use if x != null, or, if v := result, or ? as described below
.
match is an expression: it can initialize a binding, be an argument, or stand alone with its result discarded. The scrutinee evaluates once and only the selected arm runs. Save this complete example as payment.ms and run ms run payment.ms:
enum Payment {
Paid(receipt String)
Declined(reason String)
Pending(reference String)
}
fn describe(payment Payment) String {
match payment {
Paid(receipt) => {
return f"Paid: {receipt}"
}
Declined(reason) => {
return f"Declined: {reason}"
}
Pending(reference) => {
return f"Pending: {reference}"
}
}
}
fn main() Void {
print(describe(Payment.Paid("receipt-42")))
}Paid: receipt-42Each arm handles one case and gives its payload a local name. A newly added case needs an arm unless the match has a wildcard. Guards, ranges, nested case patterns and combined patterns are rejected; use another statement after binding the payload. Literal arms are described in matching literals .
Keep match flow flat#
Nested match is an anti-pattern. Use early returns, propagate errors with ?, narrow Optionals with if x != null or or, or call a small helper (the interface handler below shows a helper).
ms check --only lintreports MSL107 at each inner match, including inside inline callbacks. Helpers and sequential matches are fine. The type checker still accepts nesting; this is style only.- An
Optionalhas nosomepattern: the present arm is a bare lowercase name besidenull =>(v =>binds the payload). A two-arm payload/nullmatch is MSL108. Useif x != nullorx or fallback(Optionals ).
Matching a Result with only ok and error arms is flagged the same way as advisory MSL109. Use ?, if value := result { ... } with } else {, or a Result method such as get_or(default), is_error, or err.
Matching literals#
A match on an Int, String, or Bool takes literal arms: number literals (with an optional -), plain text literals, true, and false. Arms are tested in order; each value may appear once. A final _ is required unless true and false are both covered. Arms bind nothing.
fn name(count Int) String {
match count {
0 => return "none"
1 => return "one"
_ => return "many"
}
}Computed values, interpolated text, ranges, and Float scrutinees are not literal patterns; use if and else if.
Arm values#
An arm may hold statements then a final expression, which is its value; ending in a statement gives Void. Value-producing arms must share a compatible type, taken from the annotation or expected type, or else from the arms themselves. Arms that exit via return, break, continue, or Never contribute no value.
enum Cents {
Valid(amount Int)
Invalid
}
fn total(cents Cents) Result[Int, Error] {
amount := match cents {
Valid(value) => {
value
}
Invalid => {
return error(Error("Invalid amount"))
}
}
return ok(amount)
}return exits the enclosing function even from inside another expression, running cleanup; break and continue target the enclosing loop; an anonymous function has its own return boundary.
Short arms put the value after the arrow (null => 0). End an effect-only arm with void if its last call returns something else. A standalone match discards its result, so arms need not agree; a used result needs every arm to produce it. An empty arm or block is void; there is no pass.
Payload patterns#
Payloads bind by position in field order: exactly one identifier or _ per field, even though constructors use named fields. Nullary cases are a bare name without ().
A lone lowercase arm binds a payload only when matching an Optional; on another enum it names a payloadless variant, including a variant that is named in lowercase.
enum Position {
Point(x, y Int)
Unknown
}
fn horizontal(position Position) Int {
match position {
Position.Point(horizontal_value, _) => {
return horizontal_value
}
Position.Unknown => {
return 0
}
}
}Point(x: local, y: other) =>is a parse error;Point(x) =>is an arity error. Repeated names are rejected;_may repeat.- Payload bindings and the arm body share a nested scope.
- An unqualified case resolves within the scrutinee’s type; a qualified case must belong to that exact type (
Other.Point(...)never matchesPosition). Constructors resolve per alternative construction . - Payload names always bind fresh.
error(NotFound)matches every error and does not test forNotFound; binderror(cause)and passcauseto a helper that matches the cases.
ms check --only lint reports MSL106 (a lint error; ms check --only types accepts it) when a capitalized payload name coincides with a known case or type name. Use a name like cause or _cause.
Exhaustiveness#
Arms never fall through, and a missing case is a compile error. _ => is the wildcard: allowed once, last, binds nothing, and covers the remaining cases. Rejected: duplicate or unknown cases (qualified and unqualified spellings of one case are duplicates), an arm after the wildcard, and a wildcard after every case is covered.
fn paid(payment Payment) Bool {
match payment {
Paid(_) => {
return true
}
_ => {
return false
}
}
}Adding a case breaks matches without a wildcard; a wildcard absorbs it. Return completeness follows the function return rules .
Optional and Result values#
Optional
and Result
are enums, but do not match them. Narrow Optionals with if value != null { ... } or value or fallback; handle Results with ?, if value := result { ... }, get_or(default), or is_error() with err().
Interface type patterns#
An interface value keeps its concrete receiver. ConcreteType(receiver) recovers it for a particular type, and _ => handles the rest. This is not a constructor call.
interface Shape {
fn area() Int
}
type Square {
side Int
}
fn Square.area() Int => return self.side * self.side
fn describe(shape Shape) String {
match shape {
Square(square) => return f"square {square.side}"
_ => {
return f"area {shape.area()}"
}
}
}- The type is a local or imported nominal type or enum that satisfies the scrutinee’s exact interface.
- Give exactly one receiver name or
_, even for a payloadless enum. The binding has the concrete type. Native opaque receivers fall to the wildcard. - Generic patterns name the full application:
Boxed[Int](value)differs fromBoxed[String]; an in-scope parameter may be an argument (Boxed[T](value)). The first arm matching the exact runtime type wins; duplicate patterns are rejected. A pattern cannot name another interface, a bare type parameter, or a single enum case. - A final wildcard is required because interfaces are open. It binds nothing; use the original value for generic handling.
- The receiver is not copied, and matching adds no cleanup and catches no faults or cancellation. See interface conversion .
Matching resource references#
Matching a borrowed value borrows its payloads. Matching an owned value at its last use can move its payloads, which transfers responsibility for their cleanup. Resource parts that are not moved still close. See mutation and references
. Destructuring
uses brackets or braces, while match cases use Case(payload).