Arrays in Rust

Our first program will demonstrate how to work with arrays in Rust. Here’s the full source code with explanations:

fn main() {
    // Here we create an array `a` that will hold exactly 5 `i32`s.
    // The type of elements and length are both part of the array's type.
    // By default, an array is initialized with zeros.
    let mut a: [i32; 5] = [0; 5];
    println!("emp: {:?}", a);

    // We can set a value at an index using the array[index] = value syntax,
    // and get a value with array[index].
    a[4] = 100;
    println!("set: {:?}", a);
    println!("get: {}", a[4]);

    // The len() method returns the length of an array.
    println!("len: {}", a.len());

    // Use this syntax to declare and initialize an array in one line.
    let b = [1, 2, 3, 4, 5];
    println!("dcl: {:?}", b);

    // In Rust, you can't use ... to let the compiler count elements,
    // but you can use a slice pattern to achieve a similar effect.
    let c = &[1, 2, 3, 4, 5][..];
    println!("slice: {:?}", c);

    // If you want to create an array with default values except for some indices:
    let d = [0, 0, 0, 400, 500];
    println!("idx: {:?}", d);

    // Array types are one-dimensional, but you can compose types to build
    // multi-dimensional data structures.
    let mut two_d = [[0; 3]; 2];
    for i in 0..2 {
        for j in 0..3 {
            two_d[i][j] = i + j;
        }
    }
    println!("2d: {:?}", two_d);

    // You can create and initialize multi-dimensional arrays at once too.
    let two_d = [
        [1, 2, 3],
        [4, 5, 6],
    ];
    println!("2d: {:?}", two_d);
}

To run the program, save it as arrays.rs and use rustc to compile, then run the resulting binary:

$ rustc arrays.rs
$ ./arrays
emp: [0, 0, 0, 0, 0]
set: [0, 0, 0, 0, 100]
get: 100
len: 5
dcl: [1, 2, 3, 4, 5]
slice: [1, 2, 3, 4, 5]
idx: [0, 0, 0, 400, 500]
2d: [[0, 1, 2], [1, 2, 3]]
2d: [[1, 2, 3], [4, 5, 6]]

Note that arrays in Rust are fixed-size and allocated on the stack. For more flexible, dynamically-sized sequences, Rust provides Vec<T> (vector), which is similar to std::vector in C++ or ArrayList in Java.

Arrays in Rust are zero-indexed and bounds-checked at runtime. Accessing an array out of bounds will result in a runtime panic, helping to catch and prevent buffer overflow vulnerabilities.

Rust’s type system and ownership rules provide strong guarantees about the correct use of arrays, making them safe and efficient to use in systems programming contexts.