Ownership & Borrowing · 13 min · free lesson

Slices

Slices are borrowed views into contiguous data.

Core idea

A slice borrows a range; it allocates nothing.

Coming from C? Pointer + Length to Slices covers this side by side.

Two borrowed slice views point into ranges of one underlying byte buffer.
A slice views existing contiguous data without owning another allocation.

Understand it

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. The returned &str refers to the caller's data. The function cannot safely return a slice of a local String created inside it, because that local owner would be dropped on return. The borrow checker ties the view's validity to the source data. The same reasoning applies to &items[1..3]: changing the vector's storage while the slice remains in use would invalidate the view.

Try calling first_word with "crab rust" and with "crab". Check both results, then pass a substring of a larger string. To make an independent copy, call .to_owned() or .to_string() deliberately and compare the ownership behavior. For Unicode text, slice indices are byte offsets and must fall on UTF-8 boundaries; arbitrary numeric character positions are not safe byte positions. Decide whether an API needs a borrowed view or an owned copy based on how long the result must survive.

Read the code

fn first_word(text: &str) -> &str {
    match text.find(' ') {
        Some(i) => &text[..i],
        None => text,
    }
}

No allocation, and the result cannot outlive its input.

Practice starter

fn first(text: &str) -> &str {
    &text[..3]
}

Practise this code in Playground ↗

Try it

Borrow at most count elements from the start, clamping to length. Return a subslice without allocating or panicking. In the Crabrix app, open the compiler lab and complete the supplied function in solution.rs. The reading question is a separate exercise.

What success looks like: The local compiler accepts the changed solution and the separate verification harness finishes all normal and boundary cases. Printing a success message alone does not complete this lab.

Check your understanding

What does that return type mean?

Reveal the answer
  1. A newly allocated String the caller owns
  2. A borrowed view tied to the input's lifetime
  3. A copy of the first three bytes of the input

The returned &str borrows from text, so it cannot outlive it.

Go deeper

Common misconception: “Returning &str copies the text into a new String for the caller.”

&text[..3] allocates nothing: it is a pointer and a length into the bytes text already refers to. That is why the compiler ties the result to text instead of letting it outlive the input.

  1. Find the data: text is a borrowed &str, and first owns nothing. &text[..3] builds a new pointer and length over the first three bytes of the same buffer.
  2. Predict before checking: Predict what first("crab rust") returns. Then predict what happens with first("é"), whose UTF-8 form is only two bytes long.
  3. Compare with evidence: Run both: crab rust gives cra, while é panics because byte offset 3 is past the end of the text. Slice indices count bytes, not characters.

Transfer challenge: Rewrite first as first_word from the example, using text.find(' ') instead of ..3. Call it with "crab rust" and "crab", then use the result after its source String is dropped and read the error.

Connections

  • Borrowing: References and E0502
  • Copy & Clone: When a value duplicates instead of moving
Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Slices (courseId "ownership", lessonId "slices")
Link: https://crabrix.com/learn/ownership/slices/
Goal: A slice borrows a range; it allocates nothing.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=ownership/slices) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.