Module 4Arrays & VecLesson 1 of 2318 min
Fixed Arrays [T; N]
Stack arrays, length in the type, and when interviews still use them.
Fixed-size arrays
rust
let a: [i32; 5] = [1, 2, 3, 4, 5];
let zeros = [0_i32; 10]; // 10 zerosProperties
- Length is part of the type:
[i32; 3]≠[i32; 4]
- Indexing is
O(1); out of bounds panics
- Copy if
T: Copy
Interview angle
Most problems use growable lists (Vec), but fixed arrays appear for:
- Counting sort buckets
[0; 26]for letters
- Small known sizes (RGB, coordinates)
- In-place swaps on a fixed buffer
Slice view
rust
fn sum(xs: &[i32]) -> i32 { xs.iter().sum() }
sum(&a); // array coerces to sliceChallenge
Write fn reverse_in_place(a: &mut [i32]) using two pointers.
Tips
- [T; N] length is compile-time
- Prefer &[T] in function args
- swap is built-in on slices
Try it live
Fixed Arrays [T; N]Rust 2021
Loading editor…
Output
Press Run to compile and execute.