While slicing a data collection, Rust allows us to omit either the start index or the end index or both from its syntax.
&variable[start_index..end_index];​
For example :1. Omitting the Start Index of a Slice :
fn main() {
let numbers = [1, 2, 3, 4, 5];
// omit the start index
let slice = &numbers[..3];
println!("array = {:?}", numbers);
println!("slice = {:?}", slice);
}​
Output :
array = [1, 2, 3, 4, 5]
slice = [1, 2, 3]​
Here,
&numbers[..3]
includes
..3
without the start index. This means the slice starts from index
0
and goes up to index
3
(exclusive). It is equivalent to
&numbers[0..3]
.
2. Omitting the End Index of a Slice :
fn main() {
let numbers = [1, 2, 3, 4, 5];
// omit the end index
let slice = &numbers[2..];
println!("array = {:?}", numbers);
println!("slice = {:?}", slice);
}​
Output :
array = [1, 2, 3, 4, 5]
slice = [3, 4, 5]​
Here,
&numbers[2..]
includes
2..
without the end index. This means the slice starts from index
2
and goes up to index
5
(exclusive). It is equivalent to
&numbers[2..5]
.
3. Omitting both Start and End Index of a Slice :
fn main() {
let numbers = [1, 2, 3, 4, 5];
// omit the start index and the end index
// reference the whole array
let slice = &numbers[..];
println!("array = {:?}", numbers);
println!("slice = {:?}", slice);
}​
Output :
array = [1, 2, 3, 4, 5]
slice = [1, 2, 3, 4, 5]​
Here,
&numbers[..]
includes .. without the start and end index. This means the slice starts from index 0 and goes up to index 5 (exclusive).
It is equivalent to
&numbers[0..5]
which will produce the same slice and will reference the whole array.