Skip to content

Control flow

if and match are statements, and also values when every branch gives one.

let temperature = 31
let feel = if temperature > 25 { "warm" } else { "cool" }
let advice = match feel {
"warm" => "drink water"
_ => "take a jacket"
}
print(feel + ": " + advice)
warm: drink water

match must cover every case. The compiler tells you which ones are missing, so adding a variant to an enum later shows you every place that has to handle it. Patterns can match numbers, ranges, text, tuples, enum variants and the start of a string:

fn describe(request: &Str) -> Str {
match request {
"GET /" => return "home"
"GET " + path => return "page " + path
_ => return "unknown"
}
}
print(describe(&"GET /"))
print(describe(&"GET /about"))
print(describe(&"DELETE /"))
home
page /about
unknown

for walks a range, a collection or any iterator. while repeats while a condition holds. break and continue work as usual, and a label lets them leave an outer loop.

for i in 0..3 {
print(f"round {i}")
}
let grid = [[1, 2], [3, 40], [5, 6]]
let mut found = (0, 0)
search: for (r, row) in grid.iter().enumerate() {
for (c, value) in row.iter().enumerate() {
if *value > 10 {
found = (r, c)
break search
}
}
}
print(f"{found.0},{found.1}")
let mut n = 27
let mut steps = 0
while n != 1 {
n = if n % 2 == 0 { n / 2 } else { 3 * n + 1 }
steps += 1
}
print(f"{steps} steps")
round 0
round 1
round 2
1,1
111 steps