πŸ•
World 4 Β· The Ownership Superpower

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.

The Big Idea A slice is a reference to part of a value β€” like grabbing one slice of pie instead of the whole pie. You borrow just the bit you need!

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!

Think of it like this… A whole sentence is the whole pie. A slice like &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! πŸ“‹

Ferris says: A slice borrows part of something β€” so the original value still belongs to its owner. Sharing made simple! πŸ¦€
Watch out! The first number is where you start, and the second number is where you stop (you don't include it). So 0..6 means spots 0, 1, 2, 3, 4, 5.
Try this! In the array box, change [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. πŸ•

You learned… A slice is a reference to part of a value, you slice text with &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! πŸ“¦