if condition {
// code block
} else if another_condition {
// code block
} else {
// code block
}- Key Points:
- Conditions must be
bool(no implicit conversion). ifis an expression (can return a value).- All branches must return the same type.
- Conditions must be
let number = if condition { 5 } else { 6 };Infinite loop:
loop {
println!("Loop forever!");
break; // Exit the loop
}- Loop Labels: Break/continue specific loops:
'outer: loop { loop { break 'outer; } }
- Return Values: Use
breakwith a value:let result = loop { break 42; };
while condition {
// code block
}- Example:
while x < 10 { x += 1; }
for element in collection {
// code block
}- Ranges:
for i in 0..5 { // 0 to 4 println!("{}", i); }
- Iterators:
for item in vec![1, 2, 3].iter() { println!("{}", item); }
Powerful pattern matching:
match value {
Pattern1 => expression1,
Pattern2 => expression2,
_ => default_expression, // Catch-all
}- Key Features:
- Exhaustive: All possible values must be handled.
- Patterns: Match literals, ranges, structs, enums, etc.
- Destructuring:
match some_option { Some(x) => println!("Got: {}", x), None => println!("Got nothing"), }
- Guards:
match num { x if x % 2 == 0 => println!("Even"), _ => println!("Odd"), }
Concise pattern matching:
if let Some(x) = some_option {
println!("Got: {}", x);
}- Equivalent to:
match some_option { Some(x) => println!("Got: {}", x), _ => (), }
Loop while a pattern matches:
while let Some(x) = iterator.next() {
println!("{}", x);
}return: Exits the function.break: Exits the loop.continue: Skips to the next iteration.
if/matchcan be used in assignments:let result = if condition { "yes" } else { "no" }; let num = match some_option { Some(n) => n, None => 0, };
-
Looping with Indices:
for (index, value) in vec![1, 2, 3].iter().enumerate() { println!("Index: {}, Value: {}", index, value); }
-
Conditional Loops:
while let Ok(line) = reader.read_line(&mut buffer) { println!("{}", line); }
-
Pattern Matching with Enums:
match some_result { Ok(value) => println!("Success: {}", value), Err(e) => println!("Error: {}", e), }
- Expressions vs. Statements:
if,match, and blocks ({}) are expressions (evaluate to a value).let,loop,while,forare statements (no value).
- No Parentheses: Conditions don't need parentheses (unlike C-style languages).
- No Fallthrough:
matchdoesn't fall through (unlike Cswitch).
for i in 1..=100 {
match (i % 3, i % 5) {
(0, 0) => println!("FizzBuzz"),
(0, _) => println!("Fizz"),
(_, 0) => println!("Buzz"),
_ => println!("{}", i),
}
}