|
| 1 | +# Introduction |
| 2 | + |
| 3 | +An `array` is a collection of objects of the same type `T`, stored in contiguous |
| 4 | +memory. Arrays are created using brackets `[]`, and their length, which is known |
| 5 | +at compile time, is part of their type signature `[T; length]`(...) |
| 6 | + |
| 7 | +Unlike arrays in some other languages, arrays in Rust have a fixed length. |
| 8 | + |
| 9 | + |
| 10 | +## Arrays |
| 11 | +### Defining an array |
| 12 | +We write the values in an array as a comma-separated list inside square |
| 13 | +brackets: |
| 14 | + |
| 15 | +```rust |
| 16 | +let my_array = [1, 2, 3, 4, 5]; |
| 17 | +``` |
| 18 | + |
| 19 | +We write an array’s type using square brackets with the type of each element, a |
| 20 | +semicolon, and then the number of elements in the array, like so: |
| 21 | + |
| 22 | +```rust |
| 23 | +let my_array: [i32; 5] = [1, 2, 3, 4, 5]; |
| 24 | +``` |
| 25 | + |
| 26 | +Here, `i32` is the type of each element. After the semicolon, the number 5 |
| 27 | +indicates the array contains five elements. |
| 28 | + |
| 29 | +You can also initialize an array to contain the same value for each element by |
| 30 | +specifying the initial value, followed by a semicolon, and then the length of |
| 31 | +the array in square brackets, as shown here: |
| 32 | + |
| 33 | +```rust |
| 34 | +let my_array = [3; 5]; |
| 35 | +// => [3, 3, 3, 3, 3] |
| 36 | +``` |
| 37 | + |
| 38 | +### Accessing Array Elements |
| 39 | +You can access elements of an array using indexing, like this: |
| 40 | + |
| 41 | +```rust |
| 42 | +let a = [1, 2, 3, 4, 5]; |
| 43 | + |
| 44 | +let first = a[0]; |
| 45 | +let second = a[1]; |
| 46 | +``` |
| 47 | + |
| 48 | + |
| 49 | +### Invalid Array Element Access |
| 50 | +Let’s see what happens if you try to access an element of an array that is past |
| 51 | +the end of the array. |
| 52 | + |
| 53 | +```rust |
| 54 | +let a = [1, 2, 3, 4, 5]; |
| 55 | + |
| 56 | +let sixth = a[5]; |
| 57 | +``` |
| 58 | + |
| 59 | +The above program will fail to compile with an error similar to: |
| 60 | +```txt |
| 61 | +let value = a[5]; |
| 62 | + ^^^^^^^^^^^^ index out of bounds: the length is 5 but the index is 5 |
| 63 | +``` |
| 64 | + |
| 65 | +Now consider when you don't know the index you want to access and it is provided to you via a |
| 66 | +function parameter or a user input: |
| 67 | + |
| 68 | +```rust |
| 69 | +fn access_element(index: usize) -> i32 { |
| 70 | + let a = [1, 2, 3, 4, 5]; |
| 71 | + return a[index]; |
| 72 | +} |
| 73 | + |
| 74 | +fn main() { |
| 75 | + access_element(5); |
| 76 | +} |
| 77 | +``` |
| 78 | + |
| 79 | +In this case, the Rust compiler cannot know |
| 80 | +if the index is out of bounds. The code will compile without errors but fail at |
| 81 | +runtime with the following error. |
| 82 | + |
| 83 | +```txt |
| 84 | +thread 'main' panicked at 'index out of bounds: the len is 5 but the index is 5' |
| 85 | +``` |
| 86 | + |
| 87 | + |
| 88 | +### Use as a type |
| 89 | + |
| 90 | +An array type can be used as a variable type, function parameter or return type. |
| 91 | + |
| 92 | +```rust |
| 93 | +let my_var: [i32; 5]; |
| 94 | + |
| 95 | +fn my_func(input: [i32; 5]) -> [i32; 5] {} |
| 96 | +``` |
| 97 | + |
| 98 | +### Changing array elements |
| 99 | +Like for any other variable, arrays also have to be defined using `mut` keyword |
| 100 | +to allow change. An element can be changed by using assignment operator while |
| 101 | +accessing it via an index. |
| 102 | + |
| 103 | +```rust |
| 104 | +let mut my_array = [2, 2, 3]; |
| 105 | +my_array[0] = 1; |
| 106 | +// => [1, 2, 3] |
| 107 | +``` |
| 108 | + |
| 109 | +In the above example, we access the first element via it's index 0 and assign a |
| 110 | +new value to it. |
| 111 | + |
| 112 | +## For loops |
| 113 | + |
| 114 | +It’s often useful to execute a block of code more than once. For this task, Rust |
| 115 | +provides several loops, which will run through the code inside the loop body to |
| 116 | +the end and then start immediately back at the beginning. |
| 117 | + |
| 118 | +### `for` and range |
| 119 | + |
| 120 | +The `for in` construct can be used to iterate through an `Iterator`. We will |
| 121 | +learn more about `Iterators` in later concepts. One of the easiest ways to create an iterator is to use the range notation |
| 122 | +`a..b`. This yields values from a (inclusive) to b (exclusive) in steps of one. |
| 123 | + |
| 124 | +```rust |
| 125 | +// A for loop that iterates 10 times |
| 126 | +for n in 0..10 { |
| 127 | + // n will have a starting value of 0 |
| 128 | + // n will have the last value as 9 |
| 129 | +} |
| 130 | +``` |
| 131 | + |
| 132 | +Alternatively, `a..=b` can be used for a range that is inclusive on both ends. The above can be written as: |
| 133 | + |
| 134 | +```rust |
| 135 | +// A for loop that iterates 10 times |
| 136 | +for n in 1..=10 { |
| 137 | + // n will have a starting value of 1 |
| 138 | + // n will have the last value as 10 |
| 139 | +} |
| 140 | +``` |
| 141 | + |
| 142 | +### Break and Continue a loop |
| 143 | +A for loop can be halted by using the `break` statement. |
| 144 | + |
| 145 | +```rust |
| 146 | +// A for loop that iterates 10 times |
| 147 | +for n in 1..=10 { |
| 148 | + println!(n); |
| 149 | + break; |
| 150 | +} |
| 151 | +// => 1 |
| 152 | +``` |
| 153 | + |
| 154 | +One can conditionally break a for loop as follows: |
| 155 | + |
| 156 | +```rust |
| 157 | +// A for loop that iterates 10 times |
| 158 | +for n in 1..=10 { |
| 159 | + println!(n); |
| 160 | + if n == 5 { |
| 161 | + break; |
| 162 | + } |
| 163 | +} |
| 164 | +// => 1 |
| 165 | +// => 2 |
| 166 | +// => 3 |
| 167 | +// => 4 |
| 168 | +// => 5 |
| 169 | +``` |
| 170 | + |
| 171 | +A `continue` statement can be used to skip over an iteration. |
| 172 | +```rust |
| 173 | +// A for loop that iterates 10 times |
| 174 | +for n in 1..=10 { |
| 175 | + println!(n); |
| 176 | + continue; |
| 177 | +} |
| 178 | +// => 1 |
| 179 | +``` |
| 180 | + |
| 181 | +Similar to `break`, one can also conditionally use `continue`: |
| 182 | + |
| 183 | +```rust |
| 184 | +// A for loop that iterates 10 times |
| 185 | +for n in 1..=10 { |
| 186 | + println!(n); |
| 187 | + if n >= 5 { |
| 188 | + continue; |
| 189 | + } |
| 190 | +} |
| 191 | +// => 1 |
| 192 | +// => 2 |
| 193 | +// => 3 |
| 194 | +// => 4 |
| 195 | +// => 5 |
| 196 | +``` |
| 197 | + |
| 198 | +### Looping Through an Array with `for` |
| 199 | +The following shows an example of looping through an array using the `for in` construct. |
| 200 | + |
| 201 | +```rust |
| 202 | +let a = [10, 20, 30, 40, 50]; |
| 203 | + |
| 204 | +for element in a { |
| 205 | + println!("the value is: {element}"); |
| 206 | +} |
| 207 | +``` |
| 208 | + |
| 209 | +## Iterators |
| 210 | + |
| 211 | +The `for in` construct interacts in several ways with `Iterator`s. An array |
| 212 | +implements the `Iterator` trait. Which makes it an iterator. All iterators have some |
| 213 | +very useful built-in methods. You will learn more about what a trait is in later |
| 214 | +concepts. For now let's explore the various methods. |
| 215 | + |
| 216 | +- `.iter()` allows to access each element of a collection and leaving the collection untouched and available for reuse after the loop. |
| 217 | + ```rust |
| 218 | + let a = ["Bob", "Frank", "Ferris"]; |
| 219 | + |
| 220 | + for name in a.iter() { |
| 221 | + println!(name); |
| 222 | + } |
| 223 | + // => Bob |
| 224 | + // => Frank |
| 225 | + // => Ferris |
| 226 | + |
| 227 | + println!(a); |
| 228 | + // => ["Bob", "Frank", "Ferris"] |
| 229 | + ``` |
| 230 | + |
| 231 | +- `.rev()` allows to access each element in reverse order |
| 232 | + ```rust |
| 233 | + let a = ["Bob", "Frank", "Ferris"]; |
| 234 | + |
| 235 | + for name in a.iter().rev() { |
| 236 | + println!(name); |
| 237 | + } |
| 238 | + // => Ferris |
| 239 | + // => Frank |
| 240 | + // => Bob |
| 241 | + |
| 242 | + println!(a); |
| 243 | + // => ["Bob", "Frank", "Ferris"] |
| 244 | + ``` |
| 245 | + Notice that we still used `.iter()`. Thats because arrays have a `.reverse()` |
| 246 | + method available which as the name suggest reverses the array. But this |
| 247 | + changes the array. In our example we only intended to traverse the array in |
| 248 | + reverse order not actually change. |
| 249 | + |
| 250 | +- `.enumerate()` allows to access each element along with it's index |
| 251 | + ```rust |
| 252 | + let a = ["Bob", "Frank", "Ferris"]; |
| 253 | + |
| 254 | + for (i, name) in a.iter().enumerate() { |
| 255 | + println!("{}: {}", i, name); |
| 256 | + } |
| 257 | + // => 0: Bob |
| 258 | + // => 1: Frank |
| 259 | + // => 2: Ferris |
| 260 | + |
| 261 | + println!(a); |
| 262 | + // => ["Bob", "Frank", "Ferris"] |
| 263 | + ``` |
0 commit comments