Control Flow
## Learning Objectives
- Master conditional statements (if-else)
- Work with loops (loop, while, for)
- Use match expressions
- Understand pattern matching
## if-else Expressions
### Basic if
```rust
fn main() {
let x = 5;
if x > 0 {
println!("x is positive");
}
}
```
### if-else
```rust
fn main() {
let x = -5;
if x > 0 {
println!("x is positive");
} else {
println!("x is not positive");
}
}
```
### if-else if-else
```rust
fn main() {
let x = 0;
if x > 0 {
println!("positive");
} else if x < 0 {
println!("negative");
} else {
println!("zero");
}
}
```
### if as Expression
```rust
fn main() {
let x = 5;
let sign = if x > 0 { "positive" } else { "non-positive" };
println!("{}", sign); // positive
// With multiple else if
let grade = if x >= 90 {
"A"
} else if x >= 80 {
"B"
} else if x >= 70 {
"C"
} else {
"F"
};
}
```
### Comparison Operators
```rust
// == Equal
// != Not equal
// > Greater than
// < Less than
// >= Greater than or equal
// <= Less than or equal
```
### Logical Operators
```rust
// && Logical AND
// || Logical OR
// ! Logical NOT
fn main() {
let x = 5;
let y = 10;
if x > 0 && y > 0 {
println!("Both positive");
}
if x > 0 || y > 0 {
println!("At least one is positive");
}
if !(x == 0) {
println!("x is not zero");
}
}
```
## Loop Expressions
### loop (Infinite Loop)
```rust
fn main() {
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2; // Return value from loop
}
};
println!("Result: {}", result); // 20
}
```
### while Loop
```rust
fn main() {
let mut number = 3;
while number != 0 {
println!("{}", number);
number -= 1;
}
println!("LIFTOFF!!!");
}
```
### for Loop
```rust
fn main() {
// Iterate over range
for i in 0..5 {
println!("{}", i); // 0, 1, 2, 3, 4
}
// Inclusive range
for i in 0..=5 {
println!("{}", i); // 0, 1, 2, 3, 4, 5
}
// Iterate over array
let arr = [10, 20, 30];
for element in arr {
println!("{}", element);
}
// With index
let arr = [10, 20, 30];
for i in 0..arr.len() {
println!("{}: {}", i, arr[i]);
}
}
```
### for with Range and step
```rust
fn main() {
// Range
for i in 1..=5 {
println!("{}", i);
}
// Rev (reverse)
for i in (1..=5).rev() {
println!("{}", i); // 5, 4, 3, 2, 1
}
// Step by 2
for i in (0..=10).step_by(2) {
println!("{}", i); // 0, 2, 4, 6, 8, 10
}
}
```
### Loop Labels
```rust
fn main() {
'outer: for i in 1..=3 {
'inner: for j in 1..=3 {
if j == 2 {
continue; // Skip j = 2
}
if i == 2 && j == 1 {
break 'outer; // Break outer loop
}
println!("{} {}", i, j);
}
}
}
```
## match Expressions
### Basic match
```rust
fn main() {
let x = 1;
match x {
1 => println!("one"),
2 => println!("two"),
3 => println!("three"),
_ => println!("anything else"),
}
}
```
### match with Multiple Arms
```rust
fn main() {
let x = 2;
match x {
1 | 2 | 3 => println!("one, two, or three"),
4..=6 => println!("four, five, or six"),
_ => println!("something else"),
}
}
```
### match with Ranges
```rust
fn main() {
let score = 85;
let grade = match score {
90..=100 => "A",
80..=89 => "B",
70..=79 => "C",
60..=69 => "D",
_ => "F",
};
println!("Grade: {}", grade);
}
```
### match with let Pattern
```rust
fn main() {
let msg = Some("hello");
match msg {
Some(text) => println!("{}", text),
None => println!("No message"),
}
// Equivalent with if let
if let Some(text) = msg {
println!("{}", text);
}
}
```
### match with if guard
```rust
fn main() {
let x = Some(5);
match x {
Some(n) if n > 0 => println!("positive: {}", n),
Some(n) if n == 0 => println!("zero"),
Some(n) => println!("negative: {}", n),
None => println!("none"),
}
}
```
### match with Destructuring
```rust
fn main() {
let point = (3, 5);
match point {
(0, 0) => println!("origin"),
(x, 0) => println!("on x-axis: {}", x),
(0, y) => println!("on y-axis: {}", y),
(x, y) => println!("({}, {})", x, y),
}
}
```
### match with Enum
```rust
enum Color {
Red,
Green,
Blue,
RGB(u8, u8, u8),
}
fn main() {
let color = Color::RGB(255, 0, 0);
match color {
Color::Red => println!("Red"),
Color::Green => println!("Green"),
Color::Blue => println!("Blue"),
Color::RGB(r, g, b) => println!("RGB({}, {}, {})", r, g, b),
}
}
```
## if let Expressions
### Basic if let
```rust
fn main() {
let msg = Some(42);
if let Some(n) = msg {
println!("Number is {}", n);
} else {
println!("No number");
}
}
```
### if let with else
```rust
fn main() {
let msg: Option = None;
if let Some(n) = msg {
println!("Number is {}", n);
} else {
println!("No number provided");
}
}
```
### if let with enum
```rust
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
}
fn main() {
let msg = Message::Move { x: 10, y: 20 };
if let Message::Move { x, y } = msg {
println!("Move to ({}, {})", x, y);
}
}
```
## while let Expressions
```rust
fn main() {
let mut stack = vec![1, 2, 3];
while let Some(top) = stack.pop() {
println!("Popped: {}", top);
}
}
```
## Combining Patterns
```rust
fn main() {
let result: Result = Ok(42);
match result {
Ok(n) if n > 0 => println!("positive: {}", n),
Ok(n) => println!("zero or negative: {}", n),
Err(e) => println!("Error: {}", e),
}
}
```
## Summary
- if-else for conditional execution
- if can be used as an expression (returns value)
- loop creates infinite loop, break can return value
- while loop with condition
- for loop over ranges, iterators, collections
- Loop labels for breaking nested loops
- match is exhaustive pattern matching
- Ranges: `a..b` (exclusive), `a..=b` (inclusive)
- `|` combines patterns in match arm
- if let and while let for single pattern matching
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus →