rust / beginner
Snippet
Working with Fixed-Size Arrays
Arrays in Rust are fixed-size collections of elements of the same type. They are declared using square brackets with the type and length separated by a semicolon. Access elements using zero-based indexing with square brackets. The `.len()` method returns the array length. Arrays implement the `Display` trait when displaying as a whole using `{:?}` debug format. You can create an array with all elements initialized to the same value using `[value; count]` syntax as shown with the zeros array. The `.iter()` method creates an iterator for safe iteration.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
fn main() {let numbers: [i32; 5] = [1, 2, 3, 4, 5];println!("Array length: {}", numbers.len());println!("First element: {}", numbers[0]);println!("Last element: {}", numbers[4]);let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"];for month in months.iter() {print!("{} ", month);}println!();let zeros = [0; 3];println!("Zero array: {:?}", zeros);}
Breakdown
1
let numbers: [i32; 5] = [1, 2, 3, 4, 5];
Array declaration with explicit type and 5 elements
2
numbers.len()
Method call returning the number of elements in the array
3
numbers[0]
Index access starting at 0 - first element
4
numbers[4]
Index access - last element (array length minus 1)
5
months.iter()
Creates an iterator to safely loop through array elements
6
[0; 3]
Array initialization with 3 elements all set to 0
7
{:?}", zeros)
Debug print using {:?} format for entire array