Rust slices
Date: 2024-07-24Last modified: 2024-07-24
Table of contents
Slices are a dynamically sized view into a sequence. Therefore, you can have a slice which references an array or a vector and treat them the same. –
fn main() {
let numbers = [10, 20, 30, 40, 50];
let subset_1 = &numbers[1..3];
let subset_2 = &numbers[1..=3];
println!("subset_1");
for n in subset_1 {
println!("{n}");
}
println!("subset_2");
for n in subset_2 {
println!("{n}");
}
println!("numbers_2");
let numbers_2: Vec<u8> = (1..5).collect();
for n in numbers_2 {
println!("{n}");
}
}
Possible output
subset_1
20
30
subset_2
20
30
40
numbers_2
1
2
3
4