What if you want to do something with a part of an array or vector? Perhaps your first idea is to copy that part out to another array, but Rust has a safer and more efficient solution: take a slice of the array. No copy is needed, instead you get a view into the existing array, like a string slice is a view into a string.
As an example, suppose I only need the numbers 42, 47, and 45 from our vector magic_numbers. Then I can take the following slice:
let slc = &magic_numbers[1..4]; // only the items 42, 47 and 45
The starting index 1 is the index of 42, the last index 4 points to 54, but this item is not included. The & shows that we are referencing an existing memory allocation.
Slices share the following with vectors:
- They are generic and have type &[T] for a type T
- Their size does not have to be known at compile time