Introduction
Slices let you look at parts of a collection without copying it. They help save memory and make your code faster.
Slices let you look at parts of a collection without copying it. They help save memory and make your code faster.
&collection[start..end]
A slice is a reference to a part of a collection.
The syntax uses & and range to select the part you want.
let arr = [10, 20, 30, 40, 50]; let slice = &arr[1..4];
let text = "hello world"; let part = &text[0..5];
fn print_slice(slice: &[i32]) {
for &item in slice {
println!("{}", item);
}
}
let numbers = [1, 2, 3, 4, 5];
print_slice(&numbers[2..]);This program creates a slice of the fruits array from index 1 to 2 and prints each fruit in that slice.
fn main() {
let fruits = ["apple", "banana", "cherry", "date"];
let some_fruits = &fruits[1..3];
println!("Selected fruits:");
for fruit in some_fruits {
println!("- {}", fruit);
}
}Slices do not own the data, so they cannot outlive the original collection.
Using slices helps avoid copying large amounts of data.
Slices let you access parts of collections without copying.
They make your code faster and use less memory.
Slices are safe references to data inside arrays or strings.
let arr = [1, 2, 3, 4]; let slice = &arr[1..3];&arr[1..3] creates a slice referencing elements at index 1 and 2, not a new array or deletion.arr in Rust?& before the range to create a slice.&arr[0..3], which is the correct syntax. let slice = arr[0..3]; misses the reference, B uses invalid syntax, and C uses a non-existent method.let arr = [10, 20, 30, 40, 50];
let slice = &arr[2..4];
println!("{:?}", slice);&arr[2..4] includes elements at index 2 and 3 (end index 4 is exclusive).let arr = [1, 2, 3, 4]; let slice = arr[1..5];
& reference operator needed to create a slice.&str are references to string data and support slicing with range syntax and & to get a slice.&str and slices with &s[0..3]. fn print_first_three(s: String) { println!("{}", &s[0..3]); } takes ownership (String) but slices correctly. fn print_first_three(s: &String) { println!("{}", s[0..3]); } misses & before slice. fn print_first_three(s: &str) { println!("{}", s[0..3]); } slices without &, causing error.Pass the test and this pattern moves unknown