Language reference · Section 5
Statements
5.1 Blocks
A block is a sequence of statements in { }. The opening brace goes on the
same line as the statement that owns it.
5.2 if
if score >= 90 {
drop("A")
} else if score >= 80 {
drop("B")
} else {
drop("C")
}The condition must be a bool. No parentheses are needed around it.
if is also an expression when both branches are single expressions:
plant label = if count == 1 { "item" } else { "items" }5.3 match
match picks the first arm whose pattern fits. It must cover every case;
else covers the rest.
match command {
"start" => start()
"stop", "halt" => stop()
else => drop("Unknown command: {}")
}
match shape {
Circle(r) => drop("circle of radius {}")
Square(side) => drop("square of side {}")
}Patterns are literals, kind cases with their values (section 8.6), ranges
(0..10), and _, which matches anything. match is also an expression
when every arm is a single expression.
5.4 while
plant n = 10
while n > 0 {
n -= 3
}5.5 for
for walks over a range, a list, a set, a map, a string (its characters)
or anything with an iter() method (trait Iterable).
for i in 0..10 { drop(i) }
for name in names { drop(name) }
for i, name in names.enumerate() { drop("{}: {}") }
for key, value in ages { drop("{} is {}") }The loop variable is a new constant on each iteration. A loop goes over the collection as it was when the loop started: since collections are values (section 11.1), changing the variable inside the loop changes the variable, not the loop.
plant xs = [1, 2]
for x in xs { xs.push(x) } # runs twice; xs is then [1, 2, 1, 2]There is no C-style for (init; condition; step); use a range or while.
5.6 break and continue
break leaves the innermost loop; continue starts its next iteration.
Outside a loop they are compile errors.
5.7 Expression statements
A call can stand on its own as a statement. Any other expression standing
alone (x + 1) is a compile error, since its value would be lost.