Learn the language Browse docs
On this page 5 sections
Learn the language
Control flow
if as a statement and as a value, loops with break and continue, match on unions, and why there is no bare loop.
This page shows how to branch (if / else), repeat (while, for … in, break, continue), and pick by variant (match). if has two uses: as a statement it runs a branch, and as an expression it gives back the value of the branch that ran. Both uses follow the same rules.
If runs a branch
As a statement, if runs a branch for its effects and wants no value back. Here early returns pick the answer:
fn classify(n: int) -> string {
if n < 0 { return "negative" }
if n == 0 { return "zero" }
return "positive"
}
fn main() -> int {
val label: string = classify(7)
if label == "positive" { return 1 }
return 0
}
classify(7) returns "positive", so main returns 1. An if with no else is fine as a statement, because nothing needs a value on the false path. Recursion and comparison work as you would expect:
fn fact(n: int) -> int {
if n <= 1 {
return 1
}
return n * fact(n - 1)
}
fn main() -> int {
return fact(5)
}
This exits 120. Loops are below.
If is also a value
Put the same if on the right of a val (or inside a call) and it gives back the value of the branch that ran:
val label = if score >= 90 { "A" } else { "B" }
print(if ready then "go" else "wait")
A branch is either a block or a single expression, in either position:
| Branch | Written as | Value of the branch |
|---|---|---|
| A block | if c { … } |
The value of its last statement |
| An expression | if c then a, or if c a |
The value of a |
// The same if, three ways, all with the same value.
val a = if c then 1 else 2
val b = if c 1 else 2
val d = if c {
1
} else {
2
}
fn classify2(n: int) -> string {
if n < 0 { return "negative" } // a statement: no value wanted
return if n == 0 then "zero" else "positive" // a value
}
Rules:
elseis required where a value is wanted.val y = if c 1isE0302, because the false path has no value. As a statement, noelseis fine.- Only the branch that runs is evaluated. A call, a write, or an
ok/errin the other branch does not happen. - The type of an
ifis the type of its then branch. The two branches are not compared, so keep them the same type. Anifthat gives"a"in one branch and1in the other is typedstringand sometimes holds an integer. else ifchains are one value, in either position and either spelling:if a then 1 else if b then 2 else 3. When the chain is a value, everyifin it needs its ownelse.- A branch without braces is a single expression.
if c val x = 1 else 2isE0304. Writeif c { val x = 1 } else { 2 }. thenis optional and is not a reserved word. It marks where the branch starts. The condition is parsed as a full expression, so inif n - 1the-is a subtraction and the then branch is missing (E0303).if n then -1 else 0means minus one.thenis a keyword only when a branch follows it; everywhere else it is an ordinary name, even as the whole branch (if ready then else 3is the value ofthenwhenreadyis true).
cond ? a: b is the short spelling of an if used as a value with single-expression branches: val y = ok ? 1: 0. It binds looser than every binary operator and nests to the right, and branch typing is the same if-value rule.
A block branch may compute first. Its last statement is its value, so total is n * 2 + 1 when n > 10 and 0 otherwise:
val total = if n > 10 {
val doubled = n * 2
doubled + 1
} else {
0
}
While, for-in, break, and continue
while repeats while its condition holds. for … in visits each element of a list. break leaves the loop. continue skips to the next iteration:
fn main() -> int {
var n = 0
while true {
n = n + 1
if n > 4 { break }
if n == 2 { continue }
}
return n
}
When the loop ends, n is 5, so main returns 5. The break fires when n reaches 5, which is greater than 4. The continue at 2 has no visible effect here. Adding up a list looks like this:
var mut sum = 0
for item in [1, 2, 3] {
sum = sum + item
}
while sum < 10 {
sum = sum + 1
}
for x, i in xs also binds the position i (0-based) next to the element. for x in lo..hi counts ints from lo while the counter is below hi (half-open, so empty when hi <= lo). Both bounds must be ints and are evaluated once, and no list is allocated. i works over a range too, and .. outside a for header is a parse error:
var sum = 0
for x in 0..5 {
sum = sum + x // 0+1+2+3+4 = 10
}
Name a loop to jump out of an outer one: for outer: x in xs lets break outer (or continue outer) inside any nesting hit it. A named jump to no enclosing loop is an error. while loops cannot be labeled:
var hits = 0
for outer: x in [1, 2, 3] {
for y in [4, 5, 6] {
hits = hits + 1
if y == 5 { break outer }
}
} // hits is 2
A condition can use any expression: arithmetic, comparisons, &&, ||, unary ! and -, calls, member access, arrays, object literals, and string interpolation.
Match on unions
A union is a type with several variants, and each variant can carry a value, written in parentheses. Number(int) is a variant that carries an int. An enum is the same idea without payloads:
enum Color {
Red
Green
}
union Payload {
Number(int)
Text(string)
}
match picks the arm that fits the variant and binds its payload to a name. In Shape.Circle(r), r is the radius:
union Shape { Circle(int) Square(int) Empty }
fn area(s: Shape) -> int {
match s {
Shape.Circle(r) => { return r * 3 }
Shape.Square(w) => { return w * w }
Shape.Empty => { return 0 }
}
return -1
}
fn main() -> int {
if area(Shape.Circle(4)) != 12 { return 1 }
if area(Shape.Square(3)) != 9 { return 2 }
if area(Shape.Empty) != 0 { return 3 }
return 0
}
main returns 0 when all three areas are right, and 1, 2 or 3 for the first one that is wrong.
A variant can carry more than one payload: Both(int, string) is built with one argument per payload (Pair.Both(1, "a")) and destructured with one binding per payload (Pair.Both(n, s) => …). A payload can be any named type, including a model, and arity and payload types are checked in both directions.
Like if, a match works as a statement (its arms return) or as a value (the arm’s value is the result). Matching plain values works the same way. _ is the wildcard that matches anything left over:
fn as_expression(n: int) -> int {
val v = match n {
0 => 10
1 => 20
_ => 30
}
return v
}
No bare loop
There is no unconditional loop. The word is reserved, and a loop { } body is a parse error. Write while true with a break, as the example above does. This is deliberate: the exit condition stays visible in your code.
Why reserve a keyword you cannot use?
Reserving loop leaves room for a checked form later, one where the compiler can reason about termination, without breaking programs written today. Until then, no program can use the word for something else.
What next
Next: results covers failure with result, try and catch. The full specification is the language reference.