Docs/Language/Control Flow
Control Flow
Conditionals, loops, pattern matching, and deferred cleanup.
~3 min read
On this page
If / else
fn main() -> i64 {
val x = -3;
if x > 0 {
println("positive");
} else if x < 0 {
println("negative");
} else {
println("zero");
}
val sign = if x < 0 { -1 } else { 1 }; // if as an expression
println(sign);
return 0;
}Output: negative, -1.
Loops
fn main() -> i64 {
var nums: Vec<i64> = Vec::new();
nums.push(10);
nums.push(20);
for x in nums { println(x); } // 10 20
for i in 0..3 { print(i); } // 012 (end excluded)
println("");
for i in 0..=3 { print(i); } // 0123 (end included)
println("");
for i in 0..nums.len() { // with an index
println(f"{i}: {nums.get(i)}"); // 0: 10, 1: 20
}
var k = 0;
while k < 2 { k += 1; }
loop {
k += 1;
if k == 4 { continue; }
if k > 5 { break; }
println(k); // 3, then 5
}
return 0;
}loop is a statement; break does not carry a value, and there are no loop labels. The loop variable is a single name (for (i, x) in ... does not parse). Changing a Vec inside a for loop over it is a compile error (borrow checker).
Defer
defer { ... } (braces required) runs when the function exits, not when the block ends, on every path, including an early return through ?. Deferred blocks run last registered first:
fn step(fail: bool) -> Result<i64, str> {
println("open");
defer { println("close"); } // runs on every exit path
if fail { return Result::Err("bad input"); }
println("work");
return Result::Ok(1);
}
fn run(fail: bool) -> Result<i64, str> {
val v = step(fail)?; // returns early on Err
return Result::Ok(v + 1);
}
fn main() -> i64 {
match run(false) {
Result::Ok(v) => { println(v); }
Result::Err(e) => { println(e); }
}
match run(true) {
Result::Ok(v) => { println(v); }
Result::Err(e) => { println(e); }
}
return 0;
}Output: open, work, close, 2, then open, close, bad input.
Match
match works as an expression with guards and ranges. Statement-form arms take a block: Pattern => { ...; }. More in Structs & Enums.
fn grade(score: i64) -> str {
return match score {
s if s >= 90 => "A",
s if s >= 80 => "B",
70..=79 => "C",
_ => "F",
};
}
fn main() -> i64 {
println(grade(85)); // B
println(grade(72)); // C
return 0;
}A match on an enum must cover every variant (compile error otherwise). A match on numbers or strings is not checked for exhaustiveness, so end it with _.