Slices in Rust Programming

Rust ProgrammingServer Side ProgrammingProgramming

Slices in Rust are a collection of elements of the same data type T, but unlike arrays, it is not necessary that their length is known at compile time.

In Rust, a slice is a two-word object, where the first word is actually a pointer to the data and the second word is simply the length of the slice.

Slices are much safer to use than arrays, and they allow efficient access to an array without copying. Slices are created from an array, string. They can be both mutable and not. A slice generally refers to slice of an array or a string.

Example

 Live Demo

fn main() {
   let xs: [i32; 5] = [1, 2, 3, 4, 5];
   let slice = &xs[1..5];
   println!("first element of the slice: {}", slice[0]);
   println!("the slice has {} elements", slice.len());
}

In the above example, we are taking a slice of an array and when we slice the array, we must provide the starting and the ending index inside the [] brackets to specify the array elements we want inside our slice.

Output

first element of the slice: 2
the slice has 4 elements

Slice of a string

fn main() {
   let str= String::from("Hey Tuts!!");
   let hello = &str[0..5];
   let hello=&str[..5];
   println!("the hello contains {}", hello);
}

If we want to consider slicing from the first element only, then we can avoid the first integer and simply type the ending index inside the [] brackets.

Output

the hello contains Hey T

Example

But, if we want to slice from one index to the end of the string, we can do something like this.

fn main() {
   let str= String::from("Hey Tuts!!");
   let hello = &str[3..];
   let hello=&str[3..];
   println!("the hello contains {}", hello);
}

Output

the hello contains Tuts!!
raja
Published on 03-Apr-2021 13:25:16
Advertisements