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?
answer
- two machine words
- an address plus a count
- no capacity, no ownership
- a shared borrow of the owner
basics
~20 sA &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.
solid answer
~40 s`&str` and `&[T]` are **fat pointers**: a data pointer plus a length, in bytes for `str` and in elements for `[T]`. On a 64-bit target `size_of::<&str>()` is 16 while `size_of::<&String>()` is 8. `&line[3..7]` checks the range, offsets the pointer by 3 and stores 4 as the length, so slicing is O(1) with no allocation. The slice owns nothing and has no capacity; it points into the `String`'s heap buffer, so rustc treats it as a shared borrow of `line` until its last use. `line.clear()` needs `&mut line`, so if the slice is read afterwards rustc rejects the code with E0502. That is the design: a stored byte index would go stale silently after `clear`, while a slice cannot outlive a change to its data.
code
rust · 15 linesuse std::mem::size_of;
fn main() {
println!("&String = {} bytes", size_of::<&String>());
println!("&str = {} bytes", size_of::<&str>());
println!("&[u32] = {} bytes", size_of::<&[u32]>());
println!("&mut [u8] = {} bytes", size_of::<&mut [u8]>());
println!("String = {} bytes", size_of::<String>());
let line = String::from("id,name,price");
let name: &str = &line[3..7];
// The slice points into line's heap buffer; nothing was copied.
assert_eq!(name.as_ptr(), line[3..].as_ptr());
println!("{name:?} len={}", name.len());
}go deeper
Recall that &str and &[T] are borrowed views into someone else's buffer, and that slicing never copies the data.
Explain the fat pointer: address plus length in bytes for str, in elements for [T], 16 bytes on 64-bit, and why that makes slicing O(1).
Connect the representation to the borrow checker: a live slice is a shared borrow of its owner, so clear, truncate or push are E0502 until its last use, and say why an index would be worse.
Use the representation to argue for borrowed views in parsers and protocol code: they avoid per-field allocation, and the compiler enforces that they never outlive their buffer.
## The two words inside a slice reference `str` and `[T]` are **dynamically sized types**: their length is not part of the type, so a value of type `str` cannot sit in a local variable on its own (`let x: str = ...` fails with E0277, "the size for values of type `str` cannot be known at compilation time"). You always reach them through a pointer, and that pointer carries the missing length next to the address. The Rust Reference puts it directly: pointers to slices store the number of elements, and pointers to `str` store the length in bytes. Such a pointer is called a **fat pointer** (or wide pointer), and it is twice the size of a pointer to a sized type. | Type | What it stores | Size measured with rustc 1.99.1, 64-bit | |---|---|---| | `&String` | address of the `String` struct | 8 bytes | | `String` | heap pointer, capacity, length | 24 bytes | | `&str` | address of the first byte, length in bytes | 16 bytes | | `&[u32]` | address of the first element, element count | 16 bytes | | `&mut [u8]` | the same two words, exclusive access | 16 bytes | Three consequences follow: - **Slicing is O(1).** `&line[3..7]` checks the range, adds 3 to the address and stores 4 as the length. No bytes are copied and nothing is allocated, however long the input is. - **A slice has no capacity.** It cannot grow or reallocate. That is why `&mut [T]` lets you rewrite elements but never push. - **A slice owns nothing.** Dropping a `&str` frees nothing; the bytes belong to whoever owns the buffer: a `String`, a `Vec<u8>`, or the program's read-only data for a string literal. ## Where the slice points For a `String`, the slice points into the heap buffer the `String` owns: ```rust let line = String::from("id,name,price"); let name: &str = &line[3..7]; assert_eq!(name.as_ptr(), line[3..].as_ptr()); // same address, no copy ``` For a string literal, the bytes live in the compiled binary and the literal is a `&'static str` (what `'static` means is covered with lifetimes). For a `Vec<T>` or an array, `&v[a..b]` points at element `a`. Different owners, one representation, which is why a single `&[T]` parameter accepts all of them. ## Why the owner stays borrowed Because the slice points into the owner's buffer, creating it is a **shared borrow** of the owner, and rustc keeps that borrow alive for as long as the slice is used. A signature such as `fn first_field(line: &str) -> &str` tells the compiler that the returned slice borrows from `line`, because elision ties the output to the only input reference. The Rust Book uses exactly this case to motivate slices. Compare two designs for a CSV parser that remembers where its first field ends: 1. **Store an index.** `let end = line.find(',').unwrap();` followed by `line.clear();` compiles. A later `&line[..end]` then panics because the line is empty, or, if the line was refilled, silently returns the wrong text. The index is only meaningful while the `String` is unchanged, and nothing enforces that. 2. **Store a slice.** `let field = first_field(&line);` followed by `line.clear();` and a later use of `field` is rejected: ```plaintext error[E0502]: cannot borrow `line` as mutable because it is also borrowed as immutable ``` `String::clear` takes `&mut self`, and a mutable borrow cannot coexist with the shared borrow that `field` still holds. Move the last use of `field` above the `clear` and the code compiles again, because a borrow ends at its last use. The same rule stops `truncate` on a `String`, and `push` on a `Vec`, while a slice into it is still in use. ## Common misreadings - **"A slice is a small copy."** It is a view; mutate the owner through another path and the slice would see it, which is exactly why the borrow checker forbids that while the slice lives. - **"len() counts characters."** For `str` the stored length is bytes; `"café".len()` is 5. - **"&String and &str are the same size."** `&String` is one word pointing at a struct that holds another pointer; `&str` is two words pointing at the data. ## What to say in an interview - A `&str` or `&[T]` is pointer plus length; a `&String` is a thin pointer to a struct that holds another pointer. - Slicing checks bounds and then builds a new fat pointer; it never copies the data. - The length is in bytes for `str` and in elements for `[T]`. - A live slice is a shared borrow of its owner, which is what blocks `clear` and `truncate` (E0502) until the slice's last use. - That restriction is the point: an index can go stale silently, a slice cannot.
- If `str` is a type, why can't you write `let s: str = *"abc";`?`str` is unsized: its length is not part of the type, so the compiler cannot reserve a stack slot for it, and rustc reports E0277, "the size for values of type `str` cannot be known at compilation time". You always hold it behind a pointer that carries the length: `&str`, `&mut str`, `Box<str>`. The layout of unsized types in general is covered with type layout.
- Does the borrow from a slice also stop you pushing to a `Vec` you sliced?Yes. `&v[1..]` is a shared borrow of `v`, and `Vec::push` takes `&mut self`, so pushing while the slice is still used is E0502. That protects you: a push can reallocate the buffer, and the slice's stored address would then point at freed memory. How growth and reallocation work is covered with Vec.
A slice is a sticky note reading 'from page 40, twelve pages' stuck into someone else's book: it copies no pages, and while the note is still in use the owner is not allowed to tear pages out.
- Slicing a String copies the selected bytes into a new allocation.
- A &str is the same size as a &String, one pointer.
- The length stored in a &str is a count of characters.
- A slice owns its data, so dropping it frees the bytes.
- Calling clear on a String is fine while a slice of it is still used.