|
| 1 | +--- |
| 2 | +title: Control Flow and Functions |
| 3 | +--- |
| 4 | + |
| 5 | +We'll learn how to make decisions based on conditions, repeat actions, and organize our code into reusable blocks. By the end, we'll even build a game\! |
| 6 | + |
| 7 | +--- |
| 8 | + |
| 9 | +### 1. Conditional Execution: `if` Statements |
| 10 | + |
| 11 | +Just like in other programming languages, `if` statements in Rust let your program execute different code blocks based on whether a condition is true or false. |
| 12 | + |
| 13 | +#### **Basic `if`, `else if`, `else`:** |
| 14 | + |
| 15 | +You'll find this structure very familiar: |
| 16 | + |
| 17 | +```rust |
| 18 | +fn main() { |
| 19 | + let number = 7; |
| 20 | + |
| 21 | + if number < 5 { // If this condition is true |
| 22 | + println!("Condition was true: number is less than 5"); |
| 23 | + } else if number == 5 { // Otherwise, if this condition is true |
| 24 | + println!("Condition was true: number is exactly 5"); |
| 25 | + } else { // If none of the above conditions are true |
| 26 | + println!("Condition was false: number is greater than 5"); |
| 27 | + } |
| 28 | +} |
| 29 | +``` |
| 30 | + |
| 31 | +- **Conditions Must Be `bool`:** In Rust, the condition inside an `if` statement _must_ evaluate to a **boolean** (`true` or `false`). You can't just use a number like in some other languages. |
| 32 | + ```rust |
| 33 | + // This would be an ERROR: `if number` is not allowed in Rust |
| 34 | + // if number { |
| 35 | + // println!("Number was something!"); |
| 36 | + // } |
| 37 | + ``` |
| 38 | + |
| 39 | +#### **`if` as an Expression:** |
| 40 | + |
| 41 | +A cool feature in Rust is that `if` statements are **expressions**, meaning they can return a value. This is super handy for assigning values conditionally. |
| 42 | + |
| 43 | +```rust |
| 44 | +fn main() { |
| 45 | + let condition = true; |
| 46 | + let number = if condition { // 'if' expression returns a value |
| 47 | + 5 // This value is returned if 'condition' is true |
| 48 | + } else { |
| 49 | + 6 // This value is returned if 'condition' is false |
| 50 | + }; // Note the semicolon here, as it's a statement assigning a value |
| 51 | + |
| 52 | + println!("The value of number is: {}", number); // Output: The value of number is: 5 |
| 53 | + |
| 54 | + let message = if number > 5 { |
| 55 | + "Number is greater than 5" |
| 56 | + } else { |
| 57 | + "Number is 5 or less" |
| 58 | + }; // Both branches must return the SAME TYPE! |
| 59 | + |
| 60 | + println!("Message: {}", message); |
| 61 | +} |
| 62 | +``` |
| 63 | + |
| 64 | +- **Important:** All branches of an `if` expression **must return the same type**. If one branch returns an integer and another returns a string, Rust won't compile because it can't determine the final type of the variable. |
| 65 | + |
| 66 | +--- |
| 67 | + |
| 68 | +### 2. Iterative Control Structures |
| 69 | + |
| 70 | +Repeating actions is a fundamental part of programming. Rust provides several ways to create loops. |
| 71 | + |
| 72 | +#### **`loop` (Infinite Loop with `break`):** |
| 73 | + |
| 74 | +The `loop` keyword creates an infinite loop. You'll typically use `break` to exit it based on a condition, and `continue` to skip to the next iteration. |
| 75 | + |
| 76 | +```rust |
| 77 | +fn main() { |
| 78 | + let mut counter = 0; |
| 79 | + |
| 80 | + let result = loop { // 'loop' can also return a value! |
| 81 | + counter += 1; |
| 82 | + println!("Loop count: {}", counter); |
| 83 | + |
| 84 | + if counter == 10 { |
| 85 | + break counter * 2; // Break the loop and return this value |
| 86 | + } |
| 87 | + }; // Semicolon here, as it's an expression |
| 88 | + |
| 89 | + println!("Loop finished. Result: {}", result); // Output: Loop finished. Result: 20 |
| 90 | +} |
| 91 | +``` |
| 92 | + |
| 93 | +#### **`while` Loop:** |
| 94 | + |
| 95 | +A `while` loop executes a block of code repeatedly as long as a specified condition remains true. |
| 96 | + |
| 97 | +```rust |
| 98 | +fn main() { |
| 99 | + let mut number = 3; |
| 100 | + |
| 101 | + while number != 0 { |
| 102 | + println!("{}!", number); |
| 103 | + number -= 1; // Decrement number |
| 104 | + } |
| 105 | + println!("LIFTOFF!!!"); |
| 106 | +} |
| 107 | +``` |
| 108 | + |
| 109 | +#### **`for` Loop (Iterating over Collections):** |
| 110 | + |
| 111 | +The `for` loop is the most common loop in Rust. It's used to iterate over elements in a collection (like arrays, vectors, or ranges). This is often safer and more concise than `while` loops for iterating. |
| 112 | + |
| 113 | +- **Iterating over a Range:** |
| 114 | + |
| 115 | + ```rust |
| 116 | + fn main() { |
| 117 | + // Iterate from 1 up to (but not including) 5 |
| 118 | + for number in 1..5 { |
| 119 | + println!("Number in range: {}", number); |
| 120 | + } |
| 121 | + // Iterate from 1 up to AND including 5 |
| 122 | + for number in 1..=5 { |
| 123 | + println!("Number in range (inclusive): {}", number); |
| 124 | + } |
| 125 | + } |
| 126 | + ``` |
| 127 | + |
| 128 | +- **Iterating over an Array/Vector:** |
| 129 | + |
| 130 | + ```rust |
| 131 | + fn main() { |
| 132 | + let a = [10, 20, 30, 40, 50]; |
| 133 | + |
| 134 | + for element in a.iter() { // .iter() creates an iterator over the elements |
| 135 | + println!("The value is: {}", element); |
| 136 | + } |
| 137 | + |
| 138 | + // You can also iterate with an index if needed (less common in idiomatic Rust) |
| 139 | + for (index, element) in a.iter().enumerate() { |
| 140 | + println!("Element at index {}: {}", index, element); |
| 141 | + } |
| 142 | + } |
| 143 | + ``` |
| 144 | + |
| 145 | +--- |
| 146 | + |
| 147 | +### 3. Defining and Utilizing Functions |
| 148 | + |
| 149 | +Functions are blocks of code that perform a specific task and can be reused. |
| 150 | + |
| 151 | +#### **Basic Function Syntax:** |
| 152 | + |
| 153 | +- Functions are declared using the `fn` keyword. |
| 154 | +- Parameters are type-annotated. |
| 155 | +- The return type is specified after an arrow `->`. |
| 156 | +- The last expression in a function (without a semicolon) is implicitly returned. You can also use the `return` keyword explicitly. |
| 157 | + |
| 158 | +<!-- end list --> |
| 159 | + |
| 160 | +```rust |
| 161 | +// A function that doesn't take parameters and doesn't return a value |
| 162 | +fn greet() { |
| 163 | + println!("Hello from the greet function!"); |
| 164 | +} |
| 165 | + |
| 166 | +// A function that takes parameters and returns a value |
| 167 | +fn add_numbers(x: i32, y: i32) -> i32 { // Takes two i32s, returns an i32 |
| 168 | + x + y // This is an expression, implicitly returned |
| 169 | +} |
| 170 | + |
| 171 | +// A function with an explicit return |
| 172 | +fn subtract_numbers(a: i32, b: i32) -> i32 { |
| 173 | + return a - b; // Explicit return |
| 174 | +} |
| 175 | + |
| 176 | +fn main() { |
| 177 | + greet(); // Call the greet function |
| 178 | + |
| 179 | + let sum = add_numbers(5, 7); // Call add_numbers and store the result |
| 180 | + println!("The sum is: {}", sum); // Output: The sum is: 12 |
| 181 | + |
| 182 | + let difference = subtract_numbers(10, 3); |
| 183 | + println!("The difference is: {}", difference); // Output: The difference is: 7 |
| 184 | +} |
| 185 | +``` |
| 186 | + |
| 187 | +Well, you have all the required knowladge to solve the first exercise. It is time to practice! |
0 commit comments