The Rust Programming Language — References and Borrowing — Slices
Grab a slice for yourself!
You can define a vector quite easily in Rust. But what if you want to reference just a portion of the vector without having to create a new copy of it? Slices come to the rescue. Slices are nothing but the references of a portion of a vector. Just like VectMetadata {}
we get StructMetadata {}
.
struct VectMetadata {
first_elem_index: usize,
length: usize,
capacity: usize,
}
struct SliceMetadata {
first_elem_index: usize,
length: usize,
}
fn main() {
let years: Vec<i32> = vec![2001, 2002, 2003, 2004];
let slice = &nums[0..2];
}
The only difference between the metadata of a Vector and a Slice is slice does not have capacity
. Slices can be a really nice way of referencing same piece of memory from heap and creating a new memory in the stack. We can make slices of Vectors or even strings if you a subset of chars. Slice does not own the elements, it just references them:
The type of years is Vec<i32>
where as the type of slice is &[i32]
. You can slice the strings as well.