Google News
logo
Rust - Interview Questions
What is a string slice in Rust?
In Rust, a string slice, denoted as &str, represents a view into a portion of a string. It is a borrowed reference to a string and allows you to work with strings without taking ownership of them. String slices are widely used in Rust to efficiently manipulate and process text data.

Rust Slice with the help of examples :

A Rust slice is a data type used to access portions of data stored in collections like arrays, vectors and strings.

Suppose we have an array,
let numbers = [1, 2, 3, 4, 5];​

Now, if we want to extract the 2nd and 3rd elements of this array. We can slice the array like this,
let slice = &array[1..3];​
Here, let's look at the right-hand side of the expression,

* &numbers - specifies a reference to the variable numbers (not the actual value)
* [1..3] - is a notation for slicing the array from start_index 1 (inclusive) to end_index 3 (exclusive)

Rust Slice Example :
fn main() {
    // an array of numbers
    let numbers = [1, 2, 3, 4, 5];
    
    // create a slice of 2nd and 3rd element
    let slice = &numbers[1..3];
    
    println!("array = {:?}", numbers);
    println!("slice = {:?}", slice);
}​

Output :
array = [1, 2, 3, 4, 5]
slice = [2, 3]​
Advertisement