Array and slice
- Rust course
- Advanced
- Lesson 70/81
- 4 min
Do array operations with const generics.
Arrays and slices
Arrays ([T; N]) carry the length in the type; slices (&[T]) carry it at runtime. Going from array to slice is automatic and free; the reverse is done with a check via try_into. Arrays are value types: they can be copied, returned from functions, and are Copy with Copy elements:
let a: [i32; 3] = [1, 2, 3];
let d: &[i32] = &a; // array → slice
let b: [i32; 3] = d.try_into().unwrap(); // slice → array
let c = a; // a copy, a is still validSplitting a slice into fixed pieces
Converting a slice into equal-sized arrays lets later operations work with a fixed size:
let v = [1, 2, 3, 4, 5, 6];
let ciftler: Vec<[i32; 2]> = v
.chunks_exact(2)
.map(|c| c.try_into().unwrap()) // each piece has exactly 2 elements
.collect();Here unwrap is safe because chunks_exact(2) only produces 2-element pieces.
Practice Arrays of pairs
Convert the array let v = [1, 2, 3, 4, 5, 6]; into a Vec<[i32; 2]> with chunks_exact(2) and try_into, and print it with {:?}.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn main() {
let v = [1, 2, 3, 4, 5, 6];
let ciftler: Vec<[i32; 2]> = v.chunks_exact(2).map(|c| c.try_into().unwrap()).collect();
println!("{:?}", ciftler);
}Expected output
[[1, 2], [3, 4], [5, 6]]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the difference between <code>chunks_exact(2)</code> and <code>chunks(2)</code>?
- chunks_exact is slower
- chunks errors
- chunks_exact yields only full pieces; leftover elements are taken with remainder() Correct answer
- No difference
Explanation: Since each piece's size is known exactly, the compiler can remove bounds checks.
2 Exact pieces
let ciftler: Vec<[i32; 2]> = v
.____(2)
.map(|c| c.try_into().unwrap())
.collect();
let ciftler: Vec<[i32; 2]> = v
.chunks_exact(2)
.map(|c| c.try_into().unwrap())
.collect();
Explanation: chunks_exact yields only full-size pieces.
3 Conversion and method
| Term | Meaning |
|---|---|
[T; N] → &[T] |
Automatic |
&[T] → [T; N] |
try_into |
windows(2) |
Overlapping pieces |
chunks_exact(n) |
Exact, non-overlapping |