Control flow
if and match
Section titled “if and match”if and match are statements, and also values when every branch gives
one.
let temperature = 31let feel = if temperature > 25 { "warm" } else { "cool" }let advice = match feel { "warm" => "drink water" _ => "take a jacket"}print(feel + ": " + advice)warm: drink watermatch 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 /"))homepage /aboutunknownfor 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 = 27let mut steps = 0while n != 1 { n = if n % 2 == 0 { n / 2 } else { 3 * n + 1 } steps += 1}print(f"{steps} steps")round 0round 1round 21,1111 steps