bhylu.com

Advertisements

Rust Arrays

Use a fixed-length collection when the size belongs to the type.

How it works

An array stores a fixed number of elements of the same type. Its length is known in the type, which can help express a small fixed configuration or coordinate. A vector is a different choice when the number of values changes at runtime. Borrow an array as a slice when a function only needs a sequence, and avoid unnecessary copies of large arrays.

Run the code

Reviewed with Rust 1.97.0, edition 2024, using the standard library only. Save the complete download as lesson-name.rs in a separate learning folder, compile with rustc --edition=2024 lesson-name.rs and run the resulting program (lesson-name.exe on Windows). Use the actual lesson filename. The final project includes complete Cargo package files; run cargo test --offline and cargo run --offline from that separate package folder. There is no Rust browser runner; PHP, Apache and MySQL are not needed.

This complete example was executed in the stated local review environment.

Download complete source

Example

arrays.rs

fn main() {
    let counts: [u32; 3] = [3, 5, 8];
    let total: u32 = counts.iter().sum();
    assert_eq!(counts.len(), 3);
    assert_eq!(total, 16);
    println!("Three fixed counts total {total}");
}

Expected result

Three fixed counts total 16

The annotation states both the element type and the length. iter borrows the elements for summation instead of consuming the whole collection. A runtime index should use get when an out-of-range value is an expected input condition, rather than turning ordinary validation into a panic.

Primary technical reference: Rust documentation.