An array is a tightly packed, contiguous collection of elements with one uniform type and a fixed size. You can replace elements, but you cannot change the array’s length. section 2.10.1
Rust writes an array type as [T; n], where T is the element type and n is its compile-time length. Thus, [f32; 12], [u8; 3], and [u8; 4] are different types. section 2.10.1
Create arrays in two common ways:
- Use a comma-separated list, such as [1, 2, 3]. section 2.10.1
- Use a repeat expression, such as [0; 100], which repeats 0 one hundred times. section 2.10.1
- Index elements or iterate over them; indexing is bounds checked and an invalid index panics instead of returning erroneous data. section 2.10.1
Define and process several arrays
let one = [1, 2, 3]; let two: [u8; 3] = [1, 2, 3]; let blank = [0; 3]; for n in one.iter() { println!("{} + 10 = {}", n, n + 10); } let mut sum = 0; for i in 0..one.len() { sum += one[i]; } println!("{}", sum); section 2.10.1
Listing 2.21 Defining arrays and iterating over their elements
fn main() {
let one = [1, 2, 3];
let two: [u8; 3] = [1, 2, 3];
let blank1 = [0; 3];
let blank2: [u8; 3] = [0; 3];
let arrays = [one, two, blank1, blank2];
for a in &arrays {
print!("{:?}: ", a);
for n in a.iter() {
print!("\t{} + 10 = {}", n, n+10);
}
let mut sum = 0;
for i in 0..a.len() {
sum += a[i];
}
println!("\t({:?} = {})", a, sum);
}
}
Inspect the complete example showing array literals, typed arrays, repeat expressions, nested iteration, indexing, and summation. section 2.10.1
Arrays are lightweight and efficient because their elements occupy a contiguous memory block. Growable vectors add bookkeeping, while slices provide a length that is not fixed at compile time and commonly access arrays through references. section 2.10 section 2.10.1







































