Skip to content

Mojo Match

When one value can lead to many different actions, a long if/elif chain gets repetitive: if day == 1 ... elif day == 2 ... elif day == 3 .... A match statement names the value once and then lists the cases. It can also look inside values, like tuples and lists, and pull pieces out. Pattern matching is new in Mojo 1.2, and it looks a lot like Python’s match (added in Python 3.10), with a few differences we’ll point out.

def main():
var day = 3
match day:
case 1:
print("Monday")
case 2:
print("Tuesday")
case 3:
print("Wednesday")
case _:
print("Some other day")

Output:

Wednesday

day is the subject: the value being matched. Each case holds a pattern. Here the patterns are plain numbers, which match when the subject is equal to them. case _: matches anything, so it catches every day that the cases above it didn’t.

  • The cases are checked from top to bottom.
  • The first case that matches runs, and then the whole match is done. There’s no “fall-through” into the next case, so you don’t write break at the end of each one (as you would in a C or Java switch).
  • If no case matches, nothing runs, and the program simply carries on.
def main():
var level = 9
match level:
case 1:
print("Easy")
case 2:
print("Hard")
print("Level", level)

Output:

Level 9

No case matched 9, so neither print inside the match ran. Add a case _: at the end when you want to handle “everything else”.

Use | (read it as “or”) to let one case match any of several values:

def main():
var days: List[Int] = [1, 6, 9]
for d in days:
match d:
case 1 | 2 | 3 | 4 | 5:
print(d, "is a weekday")
case 6 | 7:
print(d, "is the weekend")
case _:
print(d, "is not a day of the week")

Output:

1 is a weekday
6 is the weekend
9 is not a day of the week

String literals work as patterns too, which makes match a neat way to handle commands:

def main():
var command = String("halt")
match command:
case "go" | "start":
print("Starting the engine")
case "stop" | "halt":
print("Stopping")
case _:
print("Unknown command:", command)

Output:

Stopping

The comparison is exact: "Halt" with a capital H would go to case _.

Sometimes an exact value isn’t enough; you need a range or a calculation. Put a name in the pattern and an if after it. The name matches any value and holds it, and the case only matches when the condition, called a guard, is True:

def main():
var temps: List[Int] = [-4, 12, 25]
for t in temps:
match t:
case x if x < 0:
print(x, "is freezing")
case x if x < 20:
print(x, "is cool")
case _:
print(t, "is warm")

Output:

-4 is freezing
12 is cool
25 is warm

If the guard is False, Mojo just moves on to the next case. Because cases are checked in order, the second guard only needs x < 20: anything below 0 was already taken by the first case.

You can also keep a literal pattern and give the matched value a name with as, as in case 404 as code:. And you can write case _ if ...: when you don’t need a name at all.

This one trips up Python programmers too. A bare name in a pattern doesn’t compare with a variable of the same name. It always creates a new name that matches anything:

def main():
var limit = 100
var reading = 42
match reading:
case limit:
print("At the limit:", limit)
case _:
print("Not at the limit")

Output:

At the limit: 42

case limit: made a new limit holding 42, and matched. Mojo does warn you while building. Among its warnings is this one:

hello.mojo:7:14: warning: case is unreachable; previous cases cover every value of the match subject
case _:
^

To compare with an existing variable, write == name:

def main():
var limit = 100
var reading = 42
match reading:
case == limit:
print("At the limit")
case r if r > limit:
print("Over the limit by", r - limit)
case _:
print("Under the limit")

Output:

Under the limit

The subject can be a tuple, a group of values in parentheses. Each pattern then has one part per value, and _ means “anything here”:

def where(x: Int, y: Int):
match (x, y):
case (0, 0):
print("At the origin")
case (0, _):
print("On the y axis")
case (_, 0):
print("On the x axis")
case (a, b) if a == b:
print("On the diagonal at", a)
case _:
print("Somewhere else")
def main():
where(0, 0)
where(0, 5)
where(3, 0)
where(2, 2)
where(1, 7)

Output:

At the origin
On the y axis
On the x axis
On the diagonal at 2
Somewhere else

This is where match really beats if/elif: each case shows the shape you’re looking for at a glance. Here’s the same idea for a game of rock, paper, scissors:

def winner(a: String, b: String) -> String:
match (a, b):
case (x, y) if x == y:
return "draw"
case ("rock", "scissors") | ("scissors", "paper") | ("paper", "rock"):
return "player 1"
case _:
return "player 2"
def main():
print(winner("rock", "scissors"))
print(winner("paper", "scissors"))
print(winner("rock", "rock"))

Output:

player 1
player 2
draw

match is a statement, not an expression: you can’t write var label = match x: .... The usual way to “match into a value” is a small function that returns from each case, like winner here.

Some types have a fixed set of values. A Bool is only ever True or False. When you match one of those, Mojo warns if a case is missing:

def main():
var is_member = True
match is_member:
case True:
print("10% off")

Output:

10% off

The program runs, but the build prints:

hello.mojo:3:5: warning: 'match' is not exhaustive; missing case for 'False'
match is_member:
^

In a function that has to return a value, a missing case becomes a real error, because some path would reach the end without a return:

def fizz(n: Int) -> String:
match (n % 3 == 0, n % 5 == 0):
case (True, True):
return "FizzBuzz"
case (True, False):
return "Fizz"
case (False, True):
return "Buzz"
def main():
print(fizz(3))
hello.mojo:2:5: warning: 'match' is not exhaustive; missing case for 'False, False'
match (n % 3 == 0, n % 5 == 0):
^
hello.mojo:1:5: error: return expected at end of function with results
def fizz(n: Int) -> String:
^
mojo: error: failed to run the pass manager

The warning even names the missing case. Add case (False, False): return String(n) and it works. Numbers and strings can have endless values, so Mojo doesn’t ask you to cover them all; that’s what case _ is for.

A list pattern matches by length and contents. *rest collects “everything else” in the middle or at the end:

def describe(words: List[String]):
match words:
case []:
print("Nothing to say")
case [only]:
print("One word:", only)
case [first, second]:
print("Two words:", first, "and", second)
case [first, *rest]:
print("Starts with", first, "and", len(rest), "more")
def main():
var none: List[String] = []
describe(none)
describe(["hi"])
describe(["hello", "there"])
describe(["a", "b", "c", "d"])

Output:

Nothing to say
One word: hi
Two words: hello and there
Starts with a and 3 more

[first, second] only matches a list of exactly two items, so the four-word list falls through to [first, *rest]. (Because describe asks for a List[String], the bracket literals you pass in become lists.)

Some functions can’t always give you an answer. Searching a list for a name, for example: it might not be there. Mojo’s Optional[Int] holds either .Some(value) or .None, and match can tell them apart and unwrap the value in one step:

def find(names: List[String], target: String) -> Optional[Int]:
for i, name in enumerate(names):
if name == target:
return i
return None
def main():
var names: List[String] = ["Ana", "Ben", "Cleo"]
match find(names, "Ben"):
case .Some(i):
print("Ben is at index", i)
case .None:
print("No Ben")
if case .Some(i) = find(names, "Zed"):
print("Zed is at index", i)
else:
print("No Zed")

Output:

Ben is at index 1
No Zed

case .Some(i): matches only when there is a value, and puts it in i. When you only care about one pattern, if case pattern = value: is a shorter form, with a normal else. Optional gets its own lesson later; for now, it’s enough to know that match is a clean way to handle it.

Since cases don’t fall through, break isn’t used to end a case. Inside a loop, break and continue in a case act on the loop:

def main():
for i in range(1, 8):
match i:
case 3:
continue
case 6:
break
case _:
print(i)
print("done")

Output:

1
2
4
5
done

At 3, continue skips to the next number. At 6, break ends the for loop.

Patterns can go further than this page shows. The match statements reference lists them all:

Pattern Example What it matches
Struct case Point(x=0, y=y): a struct by its fields (see Mojo Structs)
Nested case .Some(Point(x=0, y=0)): patterns inside patterns
Mutable bindings case var x: or case Point(x=ref x, y=_): a copy you can change, or a reference that changes the original

The control flow page in the Mojo manual also covers while case, a loop that runs for as long as a value matches a pattern.

Count the vowels in var word = String("education") using a for loop and a match. Print Vowels: 5.

Hint: loop with for c in word:, use one case with "a" | "e" | "i" | "o" | "u", and case _: pass for the rest.

Show solution
def main():
var word = String("education")
var vowels = 0
for c in word:
match c:
case "a" | "e" | "i" | "o" | "u":
vowels += 1
case _:
pass
print("Vowels:", vowels)

Output:

Vowels: 5

pass means “do nothing”. A case body can’t be empty, so pass fills the spot.

Write a function shipping(weight: Int, express: Bool) -> Int that uses match on the tuple (weight, express):

  • express orders always cost 20,
  • otherwise, a weight of 0 is free (0),
  • otherwise, up to 5 costs 5,
  • anything heavier costs 10.

Print shipping(3, False), shipping(3, True) and shipping(0, False) to get 5, 20 and 0.

Hint: start with case (_, True):, then use a guard like case (w, _) if w <= 5:.

Show solution
def shipping(weight: Int, express: Bool) -> Int:
match (weight, express):
case (_, True):
return 20
case (0, _):
return 0
case (w, _) if w <= 5:
return 5
case _:
return 10
def main():
print(shipping(3, False))
print(shipping(3, True))
print(shipping(0, False))

Output:

5
20
0

The express case comes first, so (0, True) costs 20, not 0. Order the cases from the most specific rule to the most general.

This program should print Wrong PIN, but it prints Welcome for every PIN. Fix it.

def main():
var pin = 4321
var entered = 1234
match entered:
case pin:
print("Welcome")
case _:
print("Wrong PIN")

Hint: what does a bare name in a case do?

Show solution
def main():
var pin = 4321
var entered = 1234
match entered:
case == pin:
print("Welcome")
case _:
print("Wrong PIN")

Output:

Wrong PIN

case pin: made a new name that matches any number. case == pin: compares entered with the existing pin variable.

  • match value: checks its case patterns from top to bottom and runs only the first match. No fall-through, no break needed.
  • Patterns can be literals (3, "stop"), alternatives with |, and _ for “anything”.
  • A name in a pattern matches anything and holds the value; add a guard with if. To compare with an existing variable, write case == name:.
  • Tuple patterns match several values at once; list patterns match by length, with *rest for the remainder.
  • match on a Bool or Optional gets an exhaustiveness check; .Some(x) and .None unwrap an Optional, and if case tests a single pattern.
  • match is a statement, not an expression. Pattern matching is new in Mojo 1.2.

Next up: functions, how to give a piece of code a name and reuse it with different inputs.

Quick check

1. With var n = 2, what prints? Cases: case 1 | 2: print("small"), then case 2: print("two").
2. You have var limit = 10. Which case checks whether the subject equals limit?
3. What happens when no case matches and there is no case _?
4. Which list does the pattern [first, second] match?