skip to content

Slices and Borrowed Views

&str and &[T] borrow part of a String or Vec as a pointer plus a length. Interviewers ask why a function should take &str rather than &String, and what slicing can panic on.

on this pageshow

questions

5

In Rust, why should a read-only function parameter be `&str` rather than `&String`, and `&[T]` rather than `&Vec<T>`?

level: juniorimportance: must knowfreq 78%

answer

  1. who is able to call it
  2. string literals are not String values
  3. Deref at the call site
  4. a default-on clippy lint

basics

~20 s

A &str or &[T] parameter accepts every borrowed form: a &String or &Vec<T> coerces to it for free, and literals, arrays and sub-slices fit too. A &String parameter rejects those and gains almost nothing, since a shared reference cannot grow the String anyway.

solid answer

~40 s

`&String` points at the `String` struct, so only a caller holding an actual `String` can pass it; `first_field("42,widget")` fails with E0308, and a sub-slice of a larger line must be copied into a new `String` first. `&str` is the borrowed view itself, and at the call site rustc applies **deref coercion**: `String: Deref<Target = str>`, so `&owned` becomes a `&str` with no copy. Through a shared reference the function cannot push or reserve anyway, and every reading method lives on `str`. The same holds for `&Vec<T>` versus `&[T]`, which also accepts arrays and sub-ranges. Clippy's warn-by-default `ptr_arg` lint flags both. The owned or `&mut` forms are right only when the function must resize (`&mut Vec<T>`) or keep the data (`String` by value).

code

rust · 23 lines
rust
fn first_field(line: &str) -> &str {
    match line.find(',') {
        Some(i) => &line[..i],
        None => line,
    }
}

fn checksum(bytes: &[u8]) -> u32 {
    bytes.iter().map(|&b| b as u32).sum()
}

fn main() {
    let owned: String = String::from("id,name,price");
    let r: &String = &owned;
    println!("{}", first_field(&owned)); // &String coerces to &str
    println!("{}", first_field(r));
    println!("{}", first_field("42,widget,9.99")); // literal is already &str
    println!("{}", first_field(&owned[3..])); // a sub-slice works too

    let v: Vec<u8> = vec![1, 2, 3];
    let arr = [4u8, 5, 6];
    println!("{} {} {}", checksum(&v), checksum(&arr), checksum(&v[1..]));
}

go deeper

for a junior

Recall the rule: read-only text is &str, a read-only sequence is &[T], and a &String parameter rejects literals and sub-slices.

for a middle

Explain deref coercion: String implements Deref with Target = str, so rustc turns &String into &str at the call site without copying, and name the clippy ptr_arg lint.

for a senior

Show API judgment across the four shapes: &str to read, &mut [T] to rewrite in place, &mut Vec<T> only to resize, and String by value when the function keeps the data.

for a principal

Treat it as a convention enforced by clippy ptr_arg in CI, so public signatures stay as callable as possible and nobody spends review time on it.

## The short rule A Rust function that only **reads** text should take `&str`, and one that only reads a sequence should take `&[T]`. A `&String` or `&Vec<T>` parameter is almost always a mistake: it accepts fewer callers and gives the function body nothing useful in return. Clippy ships a lint for exactly this, `clippy::ptr_arg`, which is warn-by-default and reports "writing `&String` instead of `&str` involves a new object where a slice will do". ## What each type actually is - **`String`** is an owned, growable buffer: a struct holding a heap pointer, a capacity and a length. - **`str`** is the text itself, a run of UTF-8 bytes with no capacity. It is unsized, so you always hold it behind a pointer. - **`&String`** is a pointer to the `String` struct. Reading a byte takes two hops: to the struct, then to its heap buffer. - **`&str`** is a pointer straight to the bytes plus a length. One hop. - **`Vec<T>`**, **`[T]`**, **`&Vec<T>`** and **`&[T]`** mirror these four exactly, with an element count instead of a byte length. | Parameter type | Who can call it | What the body can do | |---|---|---| | `&String` / `&Vec<T>` | only callers that already have that owned type | read | | `&str` / `&[T]` | owned values (by deref coercion), literals, arrays, sub-ranges | read | | `&mut [T]` | `&mut Vec<T>`, mutable arrays, mutable sub-ranges | read and overwrite elements; length fixed | | `&mut String` / `&mut Vec<T>` | only callers that already have that owned type | read, overwrite and resize | ## Why `&String` callers still work with `&str` When the expected type at a call site is known, rustc applies **deref coercion**: if `T: Deref<Target = U>`, a `&T` is converted to `&U`. `String` implements `Deref<Target = str>` and `Vec<T>` implements `Deref<Target = [T]>`, so all of these compile against `fn first_field(line: &str) -> &str`: ```rust fn main() { let owned = String::from("id,name,price"); first_field(&owned); // &String -> &str, no copy first_field("42,widget,9.99"); // a literal is already a &str first_field(&owned[3..]); // a sub-slice of the String } ``` The coercion costs nothing: it reads the pointer and length out of the `String` and builds a `&str`. No bytes are allocated or copied. Coercion also chains through several `Deref` steps, so a `&Box<String>` reaches a `&str` parameter too. The reverse does not exist. A function declared `fn first_field(line: &String)` rejects `first_field("42,widget")` with `error[E0308]: mismatched types` ("expected `&String`, found `&str`"). To call it, the caller must allocate a `String` just to lend it out, and a caller holding a slice of a larger line must copy that slice into a new `String` first. ## What `&String` would buy, and why it is nothing Through a shared reference a function cannot push, clear or reserve, so the growable part of `String` is out of reach anyway. Every reading method such a function needs, such as `len`, `find`, `split`, `parse`, `as_bytes` and `chars`, is available on `str`. The main thing a `&String` exposes that a `&str` does not is `capacity()`, which a reader almost never wants. `&Vec<T>` versus `&[T]` is the same story: `iter`, `len`, `binary_search`, `windows` and indexing all live on the slice. ## When the owned or `&mut` form is right 1. **The function changes the length.** `&mut Vec<T>` or `&mut String` is correct when the body calls `push`, `extend`, `truncate`, `retain` or `reserve`. Clippy's `ptr_arg` leaves a `&mut Vec<T>` alone when the body grows it, but flags one that is only indexed: that function wants `&mut [T]`. 2. **The function only rewrites existing elements.** Take `&mut [T]`. It can overwrite, sort and swap elements, and it accepts a whole `Vec`, an array, or one half of a split buffer. 3. **The function keeps the data.** A constructor that stores the text should take `String` by value, so a caller who already owns a `String` hands it over without a copy. Taking `&str` and calling `to_string()` inside allocates on every call, even when the caller had a buffer to give away. ## Interview checklist - Say "deref coercion" and name the `Deref` impl that drives it. - Name what a `&String` parameter rejects: string literals, sub-slices, and text borrowed from any other owner. - Mention `clippy::ptr_arg` as the automatic guard in review. - Separate the three needs: reading (`&str`, `&[T]`), rewriting in place (`&mut [T]`) and resizing (`&mut Vec<T>`, `&mut String`).

  • When is `&mut Vec<T>` the right parameter instead of `&mut [T]`?
    When the function changes the length: `push`, `extend`, `truncate`, `retain`, `reserve`. A `&mut [T]` can read, overwrite, sort and swap existing elements but its length is fixed, because a slice has no capacity and cannot reallocate. So a pixel filter takes `&mut [u8]`, while a function that appends parsed rows takes `&mut Vec<Row>`. Clippy's `ptr_arg` flags a `&mut Vec<T>` that is only indexed.
  • Why does `first_field(&owned)` compile when `first_field` takes `&str` and `owned` is a `String`?
    Deref coercion. A function argument is a coercion site, and when `T: Deref<Target = U>` rustc converts `&T` to `&U`. `String` implements `Deref<Target = str>`, so `&owned` becomes the same `&str` that `owned.as_str()` or `&owned[..]` would produce: the String's pointer and length, nothing copied. It chains, so `&Box<String>` works too.
  • Should a struct constructor that stores a name take `&str` too?
    No. If the function keeps the text, take `String` by value. A caller that already owns a `String` then moves it in without a copy, and a caller with a `&str` pays one `to_string()` it can see. Taking `&str` and converting inside forces an allocation on every call, even for callers that had a buffer to give away.

  • A &String parameter is needed to call len or find inside the function.
  • Passing &owned to a &str parameter copies the text into a new buffer.
  • A string literal can be passed where a &String parameter is expected.
  • A &mut [T] parameter can push elements, just like &mut Vec<T>.
  • &str only accepts slices written with range syntax such as &s[..].
open as a page

In Rust, what does a `&str` or `&[T]` hold at run time, and why can't a `String` be cleared while its slice is used?

level: middleimportance: must knowfreq 62%

basics

~20 s

A &str or &[T] is a fat pointer: an address into the owner's buffer plus a length, two machine words, so slicing copies nothing. The slice is a shared borrow of its owner, so String::clear is rejected with E0502 while the slice is used.

open as a page

In Rust, how do slice patterns like `[first, .., last]` and `[cmd, args @ ..]` match a `&[T]`, and when is such a match exhaustive?

level: middleimportance: should knowfreq 35%

basics

~20 s

Each slice pattern fixes a length: [] is zero, [x] exactly one, [first, .., last] two or more, and [cmd, args @ ..] one or more, binding args to the rest as a subslice. A slice match is exhaustive only when every length, zero included, is covered.

open as a page

In Rust, why do `&mut img[..mid]` and `&mut img[mid..]` held together fail with E0499, and how does `split_at_mut` fix it?

level: middleimportance: should knowfreq 50%

basics

~10 s

Each &mut img[..] calls IndexMut::index_mut(&mut img, ..), so both slices borrow all of img mutably and rustc reports E0499; it never compares index ranges. split_at_mut(mid) borrows once and returns two non-overlapping &mut [T] halves.

open as a page

A Rust CSV parser slices fields with `&line[start..end]` on untrusted input — which inputs make it panic, and how do you make it panic-free?

level: seniorimportance: should knowfreq 42%

basics

~20 s

&line[a..b] panics when b exceeds the length, when a is greater than b, and, on a str, when a or b falls inside a multi-byte character. On untrusted input use line.get(a..b), which returns None instead, or let split and find produce the boundaries.

open as a page