typestar

Arrays in Rust

Fixed-size arrays live on the stack and carry their length in the type.

fn main() {
    let zeros = [0u8; 4];
    let primes: [i32; 5] = [2, 3, 5, 7, 11];

    println!("{:?} {:?}", zeros, primes);
    println!("len {} first {}", primes.len(), primes[0]);

    let total: i32 = primes.iter().sum();
    println!("sum {total}");

    let mut grid = [[0; 3]; 2];
    grid[1][2] = 9;
    println!("{:?}", grid);
}

How it works

  1. [0u8; 4] repeats a value to fill the array.
  2. The length is part of the type, so it cannot change.
  3. iter().sum() works the same as on a Vec.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
302
Tokens
121
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 85 seconds.

Type this snippet

Step 2 of 4 in Compound values, step 8 of 39 in Language basics.

← Previous Next →

Arrays in other languages