Control Flow
If / Else #
if x > 10 {
print("big")
} else if x > 5 {
print("medium")
} else {
print("small")
}
If as Expression #
if can be used as an expression that returns a value:
let label = if x > 10 { "big" } else { "small" }
let abs = if n < 0 { -n } else { n }
If Let #
Pattern-match a value and bind it in a single expression. Useful for optionals and enums:
let maybe_val: int? = 42
if let val = maybe_val {
print("Got value: {val}")
} else {
print("No value")
}
With enum patterns:
enum Shape {
Circle(f64),
Square(f64),
}
let s = Shape::Circle(5.0)
if let Shape::Circle(r) = s {
print("Circle with radius {r}")
}
Match #
Pattern matching with exhaustive checking:
match x {
0 => print("zero"),
1 => print("one"),
n if n < 0 => print("negative"),
_ => print("other"),
}
Match as Expression #
let description = match status {
"ok" => "Success",
"err" => "Failure",
_ => "Unknown",
}
Multiple Patterns #
match key {
39;w39; | 39;W39; => move_up(),
39;s39; | 39;S39; => move_down(),
39;q39; => quit(),
_ => {},
}
Guard Clauses #
match value {
n if n < 0 => "negative",
0 => "zero",
n if n > 100 => "large",
_ => "normal",
}
Enum Destructuring #
enum Result {
Ok(int),
Err(str),
}
match result {
Result::Ok(value) => print("Success: {value}"),
Result::Err(msg) => print("Error: {msg}"),
}
Struct Destructuring #
match point {
Point { x: 0, y: 0 } => print("origin"),
Point { x, y } if x == y => print("diagonal"),
Point { x, y } => print("({x}, {y})"),
}
Nested Patterns #
match event {
Event::Click { pos: Point { x, y }, button } if button == Button::Left => {
print("clicked at ({x}, {y})")
},
_ => {},
}
See Pattern Matching for the complete pattern reference.
Loops #
For Loop with Ranges #
// Exclusive range: 0 to 9
for i in 0..10 {
print(i)
}
// Inclusive range: 0 to 10
for i in 0..=10 {
print(i)
}
For Loop with Collections #
let items = ["apple", "banana", "cherry"]
for item in items {
print(item)
}
For Loop with Destructuring #
let pairs = [(1, "one"), (2, "two"), (3, "three")]
for (num, name) in pairs {
print("{num}: {name}")
}
While Loop #
let mut count = 0
while count < 10 {
print(count)
count += 1
}
While Let #
Pattern-match in a loop condition:
while let Some(item) = queue.pop() {
process(item)
}
Loop (Infinite) #
loop {
let input = read_line()
if input == "quit" {
break
}
process(input)
}
Break and Continue #
for i in 0..100 {
if i % 2 == 0 {
continue // skip even numbers
}
if i > 50 {
break // stop at 50
}
print(i)
}