Beginner Fundamentals
Slices
A slice is a reference to a contiguous part of a collection. It lets you work with a portion of data without copying or owning it.
String slices
A string slice (&str) points to part of a String. Use a range inside brackets.
fn main() {
let phrase = String::from("Hello, Rust");
let hello = &phrase[0..5]; // characters 0 to 4
let rust = &phrase[7..11]; // characters 7 to 10
println!("{} {}", hello, rust);
}
You can omit the start or end of the range:
fn main() {
let s = String::from("slices");
let from_start = &s[..3]; // "sli"
let to_end = &s[3..]; // "ces"
let whole = &s[..]; // "slices"
println!("{} {} {}", from_start, to_end, whole);
}
Array slices
Slices also work on arrays. The type of an integer slice is &[i32].
fn main() {
let numbers = [10, 20, 30, 40, 50];
let middle = &numbers[1..4]; // [20, 30, 40]
println!("{:?}", middle);
println!("{}", middle.len()); // 3
}
Because a slice borrows the original data, the collection must stay valid while the slice is in use. This is checked by the borrow rules.