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
[0u8; 4]repeats a value to fill the array.- The length is part of the type, so it cannot change.
iter().sum()works the same as on aVec.
Keywords and builtins used here
fni32letmainmutu8
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.
Step 2 of 4 in Compound values, step 8 of 39 in Language basics.