In Rust, when would you store a `Box<[T]>` or `Box<str>` instead of a `Vec<T>` or `String`, and what do you give up?
answer
- finished data, never grows
- no capacity field
- fat pointer: address and length
- into_boxed_slice trims spare capacity
basics
~20 sUse Box<[T]> or Box<str> for data that is finished and will never grow: the handle is two words instead of three and into_boxed_slice trims spare capacity. You lose push, insert and every other length-changing method.
solid answer
~40 sA `Vec<T>` or `String` stores a pointer, a capacity and a length (24 bytes on a 64-bit target); `Box<[T]>` and `Box<str>` are fat pointers holding only the pointer and the length (16 bytes). `Vec::into_boxed_slice` and `String::into_boxed_str` discard spare capacity like `shrink_to_fit`, so the heap block is exactly as long as the data, and `into_vec` or `into_string` converts back without copying. The elements stay mutable, since a `Box<[T]>` derefs to `[T]` and supports indexing, `sort` and `iter_mut`, but `push` and every other length-changing method are gone. It pays off when many finished values are stored, such as names in an interner or fixed child lists in tree nodes.
code
rust · 21 linesuse std::mem::size_of;
fn main() {
println!("Vec<u64> {}", size_of::<Vec<u64>>());
println!("Box<[u64]> {}", size_of::<Box<[u64]>>());
println!("Box<str> {}", size_of::<Box<str>>());
let mut names = Vec::with_capacity(1024);
names.extend(["ada", "grace", "linus"].map(String::from));
println!("vec len {} cap {}", names.len(), names.capacity());
let mut frozen: Box<[String]> = names.into_boxed_slice();
frozen.sort(); // slice methods still work
println!("boxed len {}", frozen.len());
let back: Vec<String> = frozen.into_vec(); // no copy, no allocation
println!("back cap {}", back.capacity());
let region: Box<str> = String::from("eu-west-1").into_boxed_str();
println!("{region} has {} bytes", region.len());
}go deeper
Know that Box<[T]> and Box<str> are owned, fixed-length versions of Vec and String, and that you get one with into_boxed_slice or into_boxed_str.
Explain the layout: three words versus a two-word fat pointer, capacity trimmed on the way in, a free conversion on the way out, and mutable elements but no push.
Point to where it matters in production: millions of interned names, fixed child lists in tree nodes, records in a large Vec, and say why it is noise for a few values.
Treat it as an API signal: a Box<[T]> field tells readers the data is finished, so weigh that clarity and the memory saved against the friction of converting back when requirements change.
## Two kinds of owned heap sequence Rust has two owned, heap-allocated forms for a sequence of `T` and for UTF-8 text: - **`Vec<T>` and `String`** are growable buffers. Each handle stores three words: a pointer to the heap buffer, the **capacity** (how many elements the buffer can hold) and the **length** (how many it holds now). The gap between them is what makes `push` cheap on average. - **`Box<[T]>` and `Box<str>`** are boxes of **unsized** types. A slice `[T]` or a `str` has no size known at compile time, so a pointer to one is a **fat pointer**: the address plus the length. There is no capacity field, because the allocation is exactly as long as the data. On a 64-bit target, measured with rustc 1.99: | Type | `size_of` | Fields | |---|---|---| | `Vec<u64>`, `String` | 24 | pointer, capacity, length | | `Box<[u64]>`, `Box<str>` | 16 | pointer, length | | `Box<[u64; 4]>` | 8 | pointer only (length is in the type) | | `Box<u64>` | 8 | pointer only | A `Box<dyn Trait>` is also a 16-byte fat pointer, carrying a vtable pointer instead of a length; trait objects get their own lesson. ## Converting between them 1. `Vec::into_boxed_slice` and `String::into_boxed_str` **discard excess capacity**, like `shrink_to_fit`, before converting. A vector with length 3 and capacity 1024 becomes a box holding exactly 3 elements, which may mean a reallocation; when length already equals capacity no reallocation is needed. 2. `<[T]>::into_vec` and `str::into_string` turn the box back into a `Vec` or `String` **without copying or allocating**; the result's capacity equals its length, so the next `push` reallocates. 3. You can build one directly: `collect()` into `Box<[T]>` (via `FromIterator`), `Box::<str>::from("text")`, or `Box::<[T]>::from(&slice[..])` for `T: Clone`, the last two copying the borrowed data. 4. `TryFrom` converts a `Box<[T]>` into a `Box<[T; N]>` in place when the length is exactly `N`, returning the original box in `Err` otherwise. ## What you give up A `Box<[T]>` dereferences to `[T]`, so every **slice** method works: indexing, `iter`, `iter_mut`, `sort`, `binary_search`, writing through `ids[0] = 10`. It is not read-only. What disappears is every method that changes the **length**: - no `push`, `pop`, `insert`, `remove`, `extend`, `truncate` or `retain`; calling one is a compile error (E0599, no method named `push` found for `Box<[u32]>`); - no `push_str` or `clear` on `Box<str>`; - no spare capacity, so any later growth means converting back and reallocating. That loss is the point: the type documents that the data is **finished**. ## When it pays off The win is a word per value plus whatever spare capacity the builder left behind. It matters when there are many values and they never change after construction: - a symbol table or interner holding millions of names as `Box<str>`; - parsed configuration or a lookup table loaded once at startup; - tree or graph nodes whose child lists are fixed after building, where `Box<[Child]>` replaces `Vec<Child>` in every node; - struct fields in a large `Vec` of records, where 8 bytes per field multiplies. It does not pay off for a buffer that still grows, or for a handful of values where the saving is noise and the conversions only add friction. ## Reading it in an interview The good answer names three facts: the handle is two words instead of three, the conversion trims capacity and the reverse conversion is free, and the trade is losing every length-changing method. A strong answer adds that the slice itself stays mutable and gives a concrete case, such as an interner, where the saving is real.
- Why is `Box<[u32]>` 16 bytes while `Box<[u32; 2]>` is 8?An array's length is part of its type, so `[u32; 2]` is sized and a box of it is a plain pointer. A slice's length is only known at run time, so the box carries it beside the address. `TryFrom` converts a `Box<[T]>` into a `Box<[T; N]>` in place when the length is exactly `N`, and returns the original box in `Err` otherwise.
- How do you build a `Box<[T]>` without first naming a `Vec`?Collect straight into it, `let ids: Box<[u32]> = (1..=4).collect();`, because `Box<[I]>` implements `FromIterator`. `Box::<[T]>::from(&slice[..])` copies a borrowed slice for `T: Clone`, and `Box::<str>::from("text")` copies a string slice. All of them allocate exactly the needed length.
- Box<[T]> is a Box around a Vec, so it costs an extra allocation.
- Box<str> is the same size as String; it only hides methods.
- A Box<[T]> is read-only, so its elements cannot be changed.
- into_boxed_slice keeps the spare capacity for a later into_vec.
- Converting a Box<[T]> back into a Vec copies every element.