When designing a long-lived Rust API type such as a parsed HTTP request, how do you decide whether its fields borrow (`&'a [u8]`) or own their data?
answer
- copy cost versus API cost
- the parameter spreads to holders
- storage, threads and tasks
- a view plus an owned form
basics
~20 sBorrowing avoids copies but puts a lifetime parameter on every holder and pins the value to its buffer. Own data in long-lived or shared types; keep borrowed views local, with a conversion to an owned form.
solid answer
~40 sBorrowed fields like `&'a [u8]` make parsing zero-copy, but the lifetime spreads: every struct and function that holds the type must carry `'a`, the value cannot outlive the request buffer, cannot go into a cache, and cannot be handed to `thread::spawn` or most task spawners. Owned fields cost one allocation and copy per field, and in return the type moves, stores and sends freely. So I ask how long the value lives, whether it crosses a thread or task boundary, whether a profile shows the copy matters, and how far `'a` would spread. Middle grounds include one owned buffer with `Range<usize>` offsets, a shared `Arc<[u8]>` with offsets, or the std pattern of a borrowed view plus an owned form, like `Path` and `PathBuf`. My default: long-lived public types own; borrowed views stay local.
code
rust · 32 lines// Borrowed view for the hot path: no allocation per header.
struct HeaderView<'a> {
name: &'a [u8],
value: &'a [u8],
}
// Owned form for anything that outlives the request buffer.
struct OwnedHeader {
name: Box<[u8]>,
value: Box<[u8]>,
}
impl HeaderView<'_> {
fn to_owned_header(&self) -> OwnedHeader {
OwnedHeader { name: self.name.into(), value: self.value.into() }
}
}
fn keep_auth(buf: &[u8]) -> Option<OwnedHeader> {
let line = buf.split(|&b| b == b'\n').find(|l| l.starts_with(b"Authorization:"))?;
let (name, value) = line.split_at(13);
let view = HeaderView { name, value: &value[2..] };
Some(view.to_owned_header()) // copies once, then `buf` may be freed
}
fn main() {
let buf = b"Host: a\nAuthorization: Bearer t\n".to_vec();
let kept = keep_auth(&buf);
drop(buf);
let h = kept.unwrap();
println!("{} {}", h.name.len(), h.value.len());
}go deeper
Recall that a struct either borrows data with a lifetime parameter or owns copies, and that borrowed structs cannot outlive the data they point into.
Explain what each choice costs: one copy per field for owned data, and a lifetime that every holder must repeat for borrowed data.
Show the concrete limits of borrowed types: no caching past the buffer, no spawning without a copy, and the self-referential trap, with offsets as an alternative.
Set a team default, such as owned long-lived public types and local borrowed views with an owned conversion, and require profiling evidence for exceptions.
## The decision A parsed HTTP request, a configuration snapshot or a protocol message can hold its fields in two ways. **Borrowed**: `struct Request<'a> { path: &'a [u8], headers: Vec<(&'a [u8], &'a [u8])> }`, pointing into the bytes the server read. **Owned**: `struct Request { path: Box<[u8]>, headers: Vec<(Box<[u8]>, Box<[u8]>)> }`, with its own copies. Both compile and both are idiomatic. The choice is a lead's call because it is cheap to make and expensive to reverse: a lifetime parameter on a public type is part of its API. ## What borrowing costs Borrowing is **zero-copy**: no allocation per field, which matters on a hot parse path. Its price is paid by everyone who touches the type: - **The parameter spreads.** Any struct that stores a `Request<'a>` must itself become generic over `'a`, and so must the functions that pass it along. - **It cannot outlive the buffer.** It cannot go into a cache, a map that outlives the request or a value returned from the function that read the bytes. - **It cannot cross into most spawned work.** `std::thread::spawn` and typical async task spawners require data that owns itself or borrows only `'static` data, and a `Request<'a>` is neither. - **It invites self-reference.** Callers who want to keep the buffer and the parse result together end up trying to put both in one struct, which Rust rejects. ## What owning costs Owned fields cost an **allocation and a copy** per field, once, at parse time. In exchange the type is `'static`, can be stored, sent and returned freely, and every signature that mentions it is simpler. For a value that lives longer than one request, or is handed to other components, that is usually the cheaper bill overall. ## Middle grounds | Design | Copies | Lifetime parameter | Good for | |---|---|---|---| | `&'a` fields | none | yes | short-lived parsing inside one call | | Owned `Box<[u8]>` / `String` fields | one per field | no | values stored, queued or sent | | One owned buffer plus `Range<usize>` offsets | one per message | no | large messages kept whole | | Shared `Arc<[u8]>` buffer plus offsets | one per message, cheap clones | no | fan-out to several consumers | | Borrowed view plus owned form | only when converting | view only | hot path with occasional retention | The last row is the pattern the standard library itself follows: `str` and `String`, `Path` and `PathBuf`, and slice iterators such as `std::slice::Iter<'a, T>` that borrow their source. A parser exposes a `HeaderView<'a>` for inspection and a `to_owned_header()` conversion that copies only what the caller decides to keep. A borrowed-or-owned enum is another option, covered with clone-on-write types. ## How to decide 1. **How long does the value live?** If it never leaves the function that owns the buffer, borrow. If it outlives the buffer, own. 2. **Does it cross a thread or task boundary?** Spawned work generally needs owned data; borrowing forces a copy at the boundary anyway. 3. **Is the copy measurable?** Profile the parse path before paying the API cost of a lifetime. Copying a few short header values is rarely the bottleneck. 4. **How far would `'a` spread?** A lifetime confined to one module is cheap; one on a type that appears in a dozen public signatures is a standing tax on every change. 5. **Can you offer both?** A borrowed view for the hot path plus an owned form for retention keeps zero-copy where it pays and simplicity everywhere else. ## Changing your mind later Adding a lifetime parameter to a public type, or removing one, changes the type's signature, so every downstream struct, function and trait impl that names it has to change too. Inside one crate that is a large refactor; across a published crate's users it is a breaking release. That asymmetry is the strongest reason to decide deliberately at the start rather than borrowing by default and discovering the limits when a value first needs to be cached or sent to a worker. ## A team default A reasonable rule: **long-lived and public types own their data; borrowed views are local, short-lived, and come with a conversion to an owned form.** Exceptions are allowed where a profile shows the allocation matters, and they are documented on the type. That keeps lifetime parameters where they buy performance and out of the signatures that change most often, while making the trade explicit in code review rather than discovered later when a type needs to go into a cache.
- A profile shows header copies matter, but parsed requests must be queued for a worker pool. What would you do?Keep one owned or shared buffer per request, for example an `Arc<[u8]>`, and store `Range<usize>` offsets for each field. The request type has no lifetime parameter, so it can be queued and sent, and fields are sliced on access without per-field allocation.
- Is it ever right to put a lifetime parameter on a public, long-lived type?Yes, when the type is inherently a view, such as an iterator or a zero-copy decoder over caller-owned input, and callers expect to own the buffer. Then document it as a view and provide an owned conversion for anything that must be retained.
- Borrowed fields are always better because copying is always slow.
- Owned fields are always better because lifetime parameters are a code smell.
- A lifetime parameter is private to the type and does not affect its users.
- A Request<'a> borrowing a local buffer can go to std::thread::spawn because it is Send.
- Adding or removing a lifetime parameter on a public type is a minor change.