skip to content

In Rust, why does a struct that stores a `&[u8]` field need a lifetime parameter, and what must its `impl` block declare?

level: middleimportance: must knowfreq 70%

answer

  1. the struct does not own it
  2. E0106 on the field
  3. a generic parameter over regions
  4. the impl header names it too

basics

~20 s

A reference field borrows data the struct does not own, so rustc needs a lifetime parameter, as in struct HeaderParser<'a> { src: &'a [u8] }, to check no instance outlives that data. The impl must declare it as well: impl<'a> HeaderParser<'a>.

solid answer

~40 s

A field like `src: &[u8]` fails with E0106 "missing lifetime specifier", because struct field types get no lifetime elision. Writing `struct HeaderParser<'a> { src: &'a [u8], pos: usize }` makes the lifetime part of the type: a `HeaderParser<'a>` is valid only while the borrowed bytes are, so rustc rejects any use of the parser after its buffer is dropped or moved. The parameter must be declared wherever the type is named: `impl<'a> HeaderParser<'a>` introduces `'a` and applies it, while plain `impl HeaderParser` fails with E0726 "implicit elided lifetime not allowed here" (`impl HeaderParser<'_>` works when no method names the lifetime). Naming `'a` in the impl lets a method return `&'a [u8]`, a slice tied to the buffer rather than to the borrow of the parser. The annotation copies nothing and keeps nothing alive.

code

rust · 20 lines
rust
struct HeaderParser<'a> {
    src: &'a [u8], // borrowed request bytes
    pos: usize,
}

impl<'a> HeaderParser<'a> {
    fn new(src: &'a [u8]) -> Self {
        HeaderParser { src, pos: 0 }
    }

    fn remaining(&self) -> &'a [u8] {
        &self.src[self.pos..]
    }
}

fn main() {
    let buf = b"Host: example.org\r\nAccept: */*\r\n".to_vec();
    let parser = HeaderParser::new(&buf); // `parser` must not outlive `buf`
    println!("{} bytes left", parser.remaining().len());
}

go deeper

for a junior

Recall that a struct holding a reference must declare a lifetime parameter and write it on the field, and that the struct cannot be used after the data it borrows is gone.

for a middle

Explain E0106 on the field, why fields get no elision, and the impl forms: impl<'a> Type<'a> to name it, Type<'_> when unnamed, and E0726 for a bare impl.

for a senior

Show when a method should return the struct's 'a rather than the self borrow, and when two lifetime parameters are worth their noise over one.

for a principal

Treat a lifetime parameter on a type as part of its public API: every holder inherits it, so weigh it against owned fields before it spreads.

## What a reference field means A Rust struct normally **owns** its fields: when the struct is dropped, its `String`s and `Vec`s are freed with it. A field of type `&[u8]` or `&str` is different. It is a **borrow** of data that something else owns, so the struct is only valid while that other owner keeps the data alive and unchanged. The compiler has to know which borrow that is before it can check any code that uses the struct, and a struct definition gives it nowhere to look unless you name it. That name is a **lifetime parameter**. Without one, rustc rejects the definition: - `struct RequestLine { method: &[u8], path: &[u8] }` fails with **E0106** "missing lifetime specifier", once per reference field. - Lifetime elision, the shorthand that lets `fn first(s: &str) -> &str` omit lifetimes, applies to function, function-pointer and closure signatures. Struct field types get no elision. - rustc's own suggestion is the fix: introduce `'a` on the struct and write it on each reference field. ## Declaring the parameter on the struct ```rust struct HeaderParser<'a> { src: &'a [u8], pos: usize, } ``` The `'a` is a generic parameter, like `T` in `Vec<T>`, but it ranges over regions of code where a borrow is valid. Writing it makes the lifetime part of the **type**: a `HeaderParser<'a>` is only usable inside the region `'a`. In practice that means: 1. Every `HeaderParser` value is created from some concrete borrow, and `'a` is inferred from it. 2. rustc checks every use of the parser against that borrow, exactly as it would check the `&[u8]` on its own. 3. Dropping, moving or mutably borrowing the buffer while the parser is still used later is rejected (E0597 for a dropped local, E0505 for a move). Fields that are owned, like `pos: usize`, are unaffected; only the reference field carries `'a`. ## Declaring it on the impl block A lifetime parameter must be declared wherever the type is named, and an `impl` block names it. The forms you meet: | `impl` header | What rustc 1.99 does | |---|---| | `impl<'a> HeaderParser<'a>` | Accepted: declares `'a`, then applies it to the type | | `impl HeaderParser<'_>` | Accepted: anonymous lifetime, when no method needs to name it | | `impl HeaderParser` | E0726 "implicit elided lifetime not allowed here" | | `impl HeaderParser<'a>` | E0261 "use of undeclared lifetime name `'a`" | The first form is the one to reach for when a method's return type must say "this borrow comes from the buffer". Inside `impl<'a> HeaderParser<'a>`, `fn remaining(&self) -> &'a [u8]` returns a slice tied to the bytes themselves, so the caller may keep it after the parser is gone. A method that returns no borrow, such as `fn pos(&self) -> usize`, needs no lifetime at all. ## What the annotation does and does not do A lifetime parameter is a **compile-time constraint**, and a few misreadings recur in interviews: - It does **not** keep the buffer alive. The owner (a `Vec<u8>` local, say) decides when the bytes are freed; `'a` only stops the parser from being used after that point. - It does **not** copy anything. The struct holds a pointer and a length, exactly like a bare `&[u8]`. - It does **not** exist at run time. There is no field, counter or check in the compiled code. - It describes a **relationship**: the parser lives no longer than the borrowed data. It is never a duration in time. Because the struct is just a pointer, a length and an index, the usual derives still apply: `#[derive(Debug, Clone, Copy)]` compiles on `HeaderParser<'a>`, since `&'a [u8]` and `usize` are both `Copy`. Copying the parser copies the reference, never the bytes, and every copy carries the same `'a`. ## One parameter or several One `'a` shared by several reference fields is the usual choice and works whenever all of them borrow from data that outlives the struct's uses; rustc picks a region that every field's borrow can satisfy. Separate parameters, as in `struct Pair<'a, 'b>`, earn their extra noise only when a method must hand back one field's borrow with that field's own, longer lifetime, so the caller can keep it after the other source is gone. Owned fields are the alternative to both, at the price of a copy, and choosing between borrowing and owning is a design decision in its own right.

  • Should two reference fields that borrow from different buffers share one lifetime parameter?
    Usually yes: one `'a` works when both buffers outlive every use of the struct, and rustc picks a region both borrows satisfy. Use two parameters, `struct Pair<'a, 'b>`, when a method must return one field's borrow with that field's own longer lifetime, so a caller can keep it after the other buffer is freed.
  • Does every method inside `impl<'a> HeaderParser<'a>` have to mention `'a`?
    No. A method returning a plain value, like `fn pos(&self) -> usize`, needs no lifetime, and one returning `&[u8]` from `&self` gets the lifetime of the `&self` borrow by elision. You write `'a` in a method's signature only when its result should be tied to the borrowed buffer itself.

  • The lifetime parameter keeps the borrowed buffer alive as long as the struct.
  • Struct fields get lifetime elision the same way function parameters do.
  • impl HeaderParser can omit the lifetime because the struct already declares it.
  • Adding 'a makes the struct copy the borrowed bytes into itself.
  • A lifetime parameter is stored at run time to track how long data lives.