rust / beginner
Snippet
Array Basics and Iteration
Arrays in Rust have fixed size known at compile time. Access elements with zero-based indexing. Use .iter() to iterate, .enumerate() for indices. Slices (&[T]) are references to a portion of an array with dynamic length at runtime.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
fn main() {let scores: [i32; 4] = [95, 87, 92, 78];println!("Total scores: {}", scores.len());for (index, score) in scores.iter().enumerate() {println!("Score {}: {}", index + 1, score);}let first = scores[0];let last = scores[scores.len() - 1];let slice = &scores[1..3];println!("Middle two: {:?}", slice);}
Breakdown
1
let scores: [i32; 4] = [95, 87, 92, 78];
Fixed-size array of 4 i32 values
2
scores.iter().enumerate()
Creates iterator with index-value pairs
3
scores[0] and scores[scores.len() - 1]
First and last element access
4
&scores[1..3]
Slice referencing indices 1 and 2