A Slice of the Pie
You donβt always want the whole pizza β sometimes you just want one slice. π In Rust, you can borrow just a part of something instead of the whole thing. That part is called a slice.
Slicing a word out of a sentence
To take a slice of text, you give the start and end spots in square brackets, like
&s[0..5]. That means βfrom spot 0 up to (but not including) spot 5.β Counting in Rust starts at 0!
&s[0..5] is one slice you cut out β
still part of the same pie, just the piece you want.
The letters in βFerrisβ sit at spots 0, 1, 2, 3, 4, and 5 β so [0..6] grabs exactly that word! π
Slicing a piece of an array
Slices donβt only work on text. You can also slice an array β a row of items in a box.
&arr[1..3] grabs the items at spots 1 and 2.
The {:?} is a special way to print a whole list at once. Handy! π
0..6 means spots 0, 1, 2, 3, 4, 5.
[1..3] to [0..2] and press
βΆ Run. Which numbers come out now?
Quick quiz
What is a slice?
A slice borrows just the part you want β like one slice of pie. π
&s[0..5] and arrays with &arr[1..3], and counting starts at 0.
You've now mastered the Ownership Superpower β next world, we level up
to building your own data types with structs! π¦