Arrays and bounds
Quick answer
An array stores a fixed number of elements of one type. It is useful when the number of items is known in advance, such as seven daily readings.
Array length and indexing
[i32; 3] means exactly three i32 values. Indexing starts at zero; values[1] selects the second value. Out-of-bounds indexing is not permitted: a compiler may reject an obvious constant mistake, and a dynamic invalid index panics. Check index < values.len() before indexing when the index is uncertain.
fn main() { let mut scores: [i32; 3] = [10, 20, 30]; scores[1] = 25; println!("{} {}", scores[1], scores.len());}Expected stdout (not executed):
25 3Changing an element does not change the array length.
fn show(index: usize) { let readings = [3, 6, 9]; if index < readings.len() { println!("{}", readings[index]); } else { println!("outside array"); }}fn main() { show(3); }Expected stdout (not executed):
outside arrayLength three means valid indices are zero, one and two.
Common mistake
[i32; 2] and [i32; 3] are different types, not interchangeable arrays.
Try it yourself
Create an array of four readings and use a loop to calculate their sum.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Arrays and bounds — practice quiz
Choose one answer per question, then review the explanation.
Which type describes exactly four bool elements?
What is the last valid index of `[6, 8, 10, 12]`?
What should code check before indexing a nonempty array using an uncertain usize i?