Rust slice
Created By: chatGPT
In Rust, a slice is a view into a contiguous sequence of elements in a collection, allowing you to access a portion of that collection without copying it. Slices are represented by a reference to a block of memory, making them light-weight compared to full collections.
To create a slice, you can use the syntax &collection[start_index..end_index]
, where start_index
is inclusive and end_index
is exclusive. Slices can be used with arrays, vectors, and strings, and they provide a flexible way to work with parts of data.
Here’s an example of how to use slices with a vector and an array:
fn main() {
let arr = [1, 2, 3, 4, 5];
let slice_arr = &arr[1..4]; // slicing elements 1 to 3
let vec = vec![10, 20, 30, 40, 50];
let slice_vec = &vec[0..3]; // slicing the first three elements
println!("Array slice: {:?}", slice_arr);
println!("Vector slice: {:?}", slice_vec);
}
In this example, we create a slice from both an array and a vector. The output of the println!
statements will display the sliced portions:
Array slice: [2, 3, 4] Vector slice: [10, 20, 30]
Slices are particularly useful for processing subsets of data without the overhead of allocating new collections. They're also commonly used in function parameters to allow functions to accept a reference to a slice instead of a whole collection, enhancing performance and safety.
fn print_slice(slice: &[i32]) {
for &item in slice {
println!("{}", item);
}
}
fn main() {
let numbers = [5, 10, 15, 20, 25];
let slice = &numbers[1..4];
print_slice(slice);
}