Start with the idea
A slice stores a pointer and a length but owns nothing, so creating one allocates no memory. Because it borrows, the compiler will not let it outlive the String or array it points into, which rules out a dangling view.
A slice is a view into existing contiguous data. &str views UTF-8 text, while &[T] views elements such as integers in an array or vector. A slice carries a starting address and a length; it does not allocate a new buffer or become a second owner. That makes slice parameters useful for read-only APIs: a function accepting &str can read both a string literal and a portion of an owned String.
The first_word example finds a byte offset for a space, then returns either the prefix or the whole input.
Keep learning, for free
The rest of this lesson is waiting for you.
Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.
No payment details. Your account opens the complete Academy.