Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 132 · Ownership and Borrowing

Slices

Learn Rust slices: &[T] and &str, ranges, split_at, chunks, windows, binary_search, sort, slice patterns and the UTF-8 character boundary panic.

A slice is a borrowed view of a contiguous run of items inside something else: a few elements of an array, the middle of a Vec, one word inside a String. A slice does not copy anything and does not own anything. It is simply "start here, this many items".

Slices are everywhere in Rust. &str is a slice of text, &[T] is a slice of anything, and most functions in the standard library that read a sequence take one. This lesson shows how slices are made, what they look like in memory, the methods that make them powerful, how to design functions around them, and the UTF-8 trap that makes string slicing panic.

Making a slice

You create a slice by borrowing a range of a collection with &collection[start..end]. The start is included, the end is excluded:

Rust Slicing an array and a Vec

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The type of middle is &[i32]: a reference to a slice of i32. (The unsized type [i32] can never be held by value, only behind a pointer, so you always see &[T] or &mut [T].)

What a slice is in memory

A slice reference is a fat pointer: two machine words, a pointer to the first item and a length. For &str it is the pointer to the first byte and the byte length. Nothing else. That is why slicing is free: no allocation, no copying.

Rust A slice is a pointer plus a length

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

On a 64-bit system a plain reference is 8 bytes and a slice reference is 16 (pointer plus length). A Vec or String is 24: pointer, length and capacity (how much room is reserved). A slice has no capacity because it cannot grow.

Bounds are checked

An invalid range panics at run time; it never reads memory out of bounds:

Rust A range past the end (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The run ends with exit code 101 and the message range end index 5 out of range for slice of length 3. A start greater than the end gives slice index starts at 3 but ends at 1. If a range might be wrong, use get, which returns an Option instead of panicking:

Rust get returns an Option

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Slices keep the original alive and frozen

Because a slice borrows, the usual rules apply. While a shared slice is alive, the owner cannot be changed. That is the classic bug Rust prevents. Consider a "first word" function that returns an index in the old way:

Rust A slice protects you from stale results (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

TEXT
error[E0502]: cannot borrow `sentence` as mutable because it is also borrowed as immutable

If this compiled, word would point at memory that clear() had just declared empty. With an index-returning function (fn first_word_len(s: &str) -> usize) the bug would compile and give a nonsense answer later. Returning a slice ties the result to the input, and the compiler enforces that tie. See The Borrow Checker in Practice for ways to fix this class of error.

Prefer &[T] and &str in parameters

A function that only reads a sequence should take a slice, not &Vec<T> or &String. Slices accept more callers:

Rust One function, many callers

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The conversions are deref coercions: the compiler automatically turns &Vec<T> into &[T] and &String into &str at function calls. With &Vec<f64> as the parameter type, you could not pass an array or a sub-slice. The only reason to take &Vec<T> is when the function needs Vec-only methods such as capacity. If it needs to push, take &mut Vec<T>. A function taking &mut [T] can change elements in place (sort, reverse, fill) but cannot change the length.

Mutable slices

&mut [T] lets you change the elements of a piece:

Rust Changing part of a Vec through a &mut slice

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Several slice methods take &mut self (reverse, fill, swap, sort), so you can call them on a sub-range with a range index, as in data[3..].reverse().

A tour of slice methods

Slices have a very large API. These are the ones you will use daily.

Looking at the ends and splitting

Rust split_at, split_first, first and last

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

chunks and windows

chunks(n) splits into non-overlapping pieces of up to n items (the last may be shorter). windows(n) gives every overlapping run of exactly n items. They are the clean replacement for index arithmetic:

Rust chunks, chunks_exact and windows

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Prefer chunks_exact in performance-sensitive loops: every chunk has the same length, so the compiler can drop bounds checks.

Searching, sorting and deduplicating

Sorting happens in place on &mut [T], so it works on arrays, vectors and sub-slices. binary_search needs sorted input and returns Ok(index) when found or Err(where_it_would_go) when not:

Rust sort, binary_search and friends

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Note that sort_by_key is stable: equal keys keep their relative order (pear stays before kiwi). Floats have no total order (because of NaN), so Vec<f64> has no .sort(); use sort_by(|a, b| a.total_cmp(b)). Sorting, Searching and Comparison covers this in depth.

Splitting by a condition

split cuts a slice at items matching a predicate, and chunk_by (stable since Rust 1.77) groups runs of neighbours:

Rust split and chunk_by

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Slice patterns

Slices can be taken apart in match and let, which is neat for recursive code and for parsing:

Rust Matching on slices

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

More on this in Patterns in Depth.

String slices: &str

A &str is a slice of UTF-8 bytes. Slicing a string uses byte offsets, and the offsets must land on character boundaries:

Rust String slices by byte range

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Plain ASCII is easy: one character is one byte. With other scripts a character takes 2 to 4 bytes, and cutting through the middle of one is a bug Rust refuses to allow:

Rust Slicing through a character (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The program prints 6 and then panics with the message end byte index 3 is not a char boundary; it is inside 'ï' (bytes 2..4 of string). Panics are the right behaviour for a bug in your offsets, but if the offsets come from user input, check them:

Rust Safe string slicing

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Indices that come from find, char_indices or split_once are always safe boundaries. The deeper story is in String Handling in Depth.

Slices are not owned: when you need a copy

A slice is a borrow. To keep the data beyond the owner's lifetime, or to change it independently, make an owned copy with to_vec() / to_owned() (for [T]) or to_string() / to_owned() (for str):

Rust From a slice to an owned value

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

If a function returns a reference into its input, the caller's data must outlive the result (see Lifetimes). If that is inconvenient, return an owned Vec or String as above: it costs one allocation but frees callers from lifetime constraints.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. What does &numbers[1..4] contain for numbers = [10, 20, 30, 40, 50]?

    The start index is included and the end index is excluded, so indices 1, 2 and 3 are taken.
  2. 2. What is stored in a &[T] value?

    A slice reference is a fat pointer made of pointer plus length. A Vec also has a capacity; a slice cannot grow.
  3. 3. Why is fn total(v: &[i32]) better than fn total(v: &Vec<i32>)?

    Deref coercion turns &Vec<i32> and &[i32; N] into &[i32], and sub-ranges are slices already, so one signature serves all of them.
  4. 4. What happens with &"naïve"[0..3]?

    The ï occupies bytes 2 and 3 (2..4), so byte offset 3 is not a character boundary. String slicing panics at run time; str::get returns None instead.
  5. 5. Which method returns every overlapping run of exactly n items?

    windows(n) slides one item at a time. chunks(n) gives non-overlapping pieces.

Summary

  • A slice (&[T], &mut [T], &str) borrows a contiguous run of items. It is a pointer plus a length, so creating one costs nothing.
  • Range syntax: a..b, ..b, a.., .., a..=b. Out-of-range ranges panic; get(range) returns an Option.
  • Accept &[T] and &str in parameters; deref coercion lets callers pass &Vec<T>, arrays and &String.
  • Useful methods: split_at, split_first, chunks, chunks_exact, windows, chunk_by, binary_search, sort, contains, starts_with.
  • Slice patterns like [first, .., last] and [head, tail @ ..] take slices apart in match.
  • String slicing uses byte offsets that must be character boundaries; prefer get, find, char_indices, or iterating chars().
  • A slice keeps its owner borrowed. Call to_vec() / to_string() for an owned copy.

Next: Copy, Clone and Move Semantics