Rust Slice
In Rust, a slice is a reference to a contiguous subset of elements in an array or a vector. Slices are a flexible way to work with arrays and can be used to pass subsets of arrays to functions without copying the data.
You can create a slice by specifying a range of indices using the syntax array[start_index..end_index]
. Here's an example:
let my_array = [1, 2, 3, 4, 5]; let my_slice = &my_array[1..3]; println!("Slice: {:?}", my_slice);
In this example, we're creating a slice that includes elements with indices 1 and 2 of the my_array
array. The resulting slice will have the values [2, 3]
. Note that we're using a reference to the slice (&my_array[1..3]
) instead of the slice itself, since slices are borrowed from the original array.
You can also create a slice that includes all elements of an array using the ..
syntax. Here's an example:
let my_array = [1, 2, 3, 4, 5]; let my_slice = &my_array[..3]; println!("Slice: {:?}", my_slice);
In this example, we're creating a slice that includes the first three elements of the my_array
array. The resulting slice will have the values [1, 2, 3]
.
You can use slices as function arguments to pass subsets of arrays to functions without copying the data. Here's an example:
fn print_slice(slice: &[i32]) { for num in slice { println!("Number: {}", num); } } let my_array = [1, 2, 3, 4, 5]; let my_slice = &my_array[1..3]; print_slice(my_slice);
In this example, we're defining a function print_slice
that takes a slice of integers as an argument. We're then creating a slice of the my_array
array and passing it to the function. Inside the function, we're iterating over the elements of the slice using a for
loop and printing each element using the println!
macro.