Rust Slices
Slices
A slice lets you use a part of a string or a list of values, without copying it.
For example, from the text "Hello World" you can take a slice with only "Hello". The slice borrows the text, just like a reference: it only looks at the original data.
String Slices
To create a slice, write & and the variable name, followed by a range in square brackets: [start..end]:
Example
let text = String::from("Hello World");
let hello = &text[0..5];
let world = &text[6..11];
println!("{}", hello);
println!("{}", world);
Try it Yourself »
Just like in a for loop, the start index is included, and the end index is not. The first character has index 0:
| Character | H | e | l | l | o | (space) | W | o | r | l | d |
|---|---|---|---|---|---|---|---|---|---|---|---|
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
&text[0..5] takes index 0 to 4 ("Hello"), and &text[6..11] takes index 6 to 10 ("World").
Leave Out the Start or End
If the slice starts at the beginning, you can leave out the first number. If it goes to the end, you can leave out the last number. With no numbers, the slice is the whole string:
Example
let text = String::from("Hello World");
println!("{}", &text[..5]);
println!("{}", &text[6..]);
println!("{}", &text[..]);
Try it Yourself »
You Already Know &str
The &str type, which you have used since the Data Types chapter, is a string slice. A text in double quotes, like "Hello", is a slice of text that is stored inside your program.
That is why a function with a &str parameter works with both a text in quotes and a slice of a String:
Example
fn greet(name: &str) {
println!("Hello, {}!", name);
}
fn main() {
greet("Liam");
let full_name = String::from("Jenny Smith");
greet(&full_name[..5]);
}
Try it Yourself »
Array Slices
Slices also work with arrays. An array is a list of values in square brackets, which you will learn more about in the Arrays chapter. Use {:?} to print all values of a slice:
Example
let numbers = [10, 20, 30, 40, 50];
let middle = &numbers[1..4];
println!("{:?}", middle);
println!("{}", middle.len());
Try it Yourself »
Slices as Function Parameters
A function that takes a slice (&[i32]) can work with a whole array, or with just a part of it:
Example
fn sum(numbers: &[i32]) -> i32 {
let mut total = 0;
for n in numbers {
total += n;
}
total
}
fn main() {
let scores = [3, 7, 5, 9];
println!("{}", sum(&scores));
println!("{}", sum(&scores[..2]));
}
Try it Yourself »
sum(&scores) adds all four numbers. sum(&scores[..2]) only adds the first two: 3 + 7.
Out of Range
If the range goes past the end of the string, the program stops with an error:
Example
let text = String::from("Hello World");
let part = &text[0..20]; // Error
println!("{}", part);
Try it Yourself »
The text "Hello World" has 11 characters, so the end index can be at most 11.
Note: String slice indexes count bytes, not characters (see String Methods). For English letters, one character is one byte, so the indexes are the same.