In this tutorial, we will learn how we can access slices of collection such as vectors, arrays, strings, etc.
Rust Create Slice
As stated in the section above, a slice is a borrowed type that holds the pointer to the address of the data.
Hence, we create a slice by taking a portion of existing data container. We cannot create a slice like we would a normal variable.
To create a slice, we specify the starting and ending index inside a pair of square brackets. The starting and ending index is separated using double dot notation.
We can express this syntax as shown:
&some_string[start_index..end_index];
Note that we can slice any valid collection in Rust. Take the example below that creates a slice from a String type.
let url = "linuxhint.com";
let slice = &url[0..9];
println!("{}", slice);
}
The code above creates a slice of a string starting from index 0 to index 9. Note that the last is exclusive. This means that the slice will contain the value from start to end index – 1.
Note the & operator? This is because the slice is a reference to the actual data in the specified collection.
The code above should return:
Rust also allows us to skip the starting and end index. For example, if we are starting the slice from index 0, we can omit the 0 and just set the ending index. An example is as shown:
let url = "linuxhint.com";
let slice = &url[..9];
println!("{}", slice);
}
Note that the above example sets the index range as ..9. This means start from index 0 to index 9.
We can do the same for ending index. Consider the example code shown below:
let url = "linuxhint.com";
let slice = &url[9..];
println!("{}", slice);
}
This should return:
Apart from a string, you can have a slice of an array. An example is as shown below:
let arr = [100,200,300,400,500];
let slice = &arr[1..3];
println!("{:?}", slice);
}
This should return an array slice with the values in the specified range.
We can slice a vector as shown:
let vec = vec!["a","b","c","d","e"];
let slice = &vec[1..=4];
println!("{:?}", slice);
}
Mutable Slice
We can also create mutable slices by setting the mut keyword in a slice. An example is as shown:
let arr = [100,200,300,400,500];
let mut slice = &arr[1..3];
println!("{:?}", slice);
}
You can mutate the returned array as you see fit.
Conclusion
This guide covers the fundamentals of working with slices in the Rust language. You can check the documentation to explore further.
Thanks for reading!