In Rust, why does collecting lines from `fn next_line(&mut self) -> Option<&[u8]>` on a `HeaderParser<'a>` fail with E0499, and how does `&'a [u8]` fix it?
answer
- two borrows in one method
- elision picks the receiver
- each line extends the call
- name the struct's parameter
basics
~20 sWith the output elided, each returned slice is tied to the &mut self borrow, so a line kept alive keeps the parser mutably borrowed and the next call is E0499. Returning &'a [u8] ties the slice to the buffer instead.
solid answer
~40 sInside `impl<'a> HeaderParser<'a>`, `fn next_line(&mut self) -> Option<&[u8]>` gets its output lifetime from `&mut self` by elision, so every returned line extends that mutable borrow of the parser. Pushing lines into a `Vec` keeps them alive, and the next `p.next_line()` fails with E0499 "cannot borrow `p` as mutable more than once at a time". Writing `Option<&'a [u8]>` says the line borrows the request bytes, not the call: the `&mut self` borrow ends on return, the loop compiles, and the lines even outlive the parser. It works because slicing through the shared `&'a [u8]` field yields `'a` data. With a `&'a mut [u8]` field the same signature is rejected until you move the slice out with `mem::take` and `split_at_mut`.
code
rust · 31 linesstruct HeaderParser<'a> {
src: &'a [u8],
pos: usize,
}
impl<'a> HeaderParser<'a> {
fn new(src: &'a [u8]) -> Self {
HeaderParser { src, pos: 0 }
}
// `'a`, not the elided `&mut self` lifetime: the line borrows the buffer.
fn next_line(&mut self) -> Option<&'a [u8]> {
let rest = &self.src[self.pos..];
if rest.is_empty() {
return None;
}
let end = rest.iter().position(|&b| b == b'\n').map_or(rest.len(), |i| i + 1);
self.pos += end;
Some(&rest[..end])
}
}
fn main() {
let buf = b"Host: a\nAccept: */*\n".to_vec();
let mut p = HeaderParser::new(&buf);
let mut lines = Vec::new();
while let Some(line) = p.next_line() {
lines.push(line);
}
drop(p); // the lines borrow `buf`, not the parser
println!("{}", lines.len());
}go deeper
Recall that a method returning a reference ties it to self unless you say otherwise, and that a struct's own lifetime name can be used in method signatures.
Explain how elision binds the output to &mut self and why a live result keeps the whole parser mutably borrowed across loop iterations.
Diagnose E0499 and E0502 from method signatures, return 'a for borrowed views, and use mem::take with split_at_mut for &'a mut fields.
Review iterator-like APIs for this mistake early: an output tied to self forces every caller to copy or restructure, and fixing the signature later is a breaking change.
## Two lifetimes in one method A method on `HeaderParser<'a>` that takes `&mut self` sees **two** borrows, and they are not the same: - `'a`, the borrow of the request bytes, declared on the struct and on `impl<'a> HeaderParser<'a>`; - the anonymous lifetime of `&mut self`, which covers only this one call's exclusive access to the parser. When you write `fn next_line(&mut self) -> Option<&[u8]>`, the output has no named lifetime, so the method rule of lifetime elision ties it to `&mut self`. The returned slice then counts as a continuation of that mutable borrow of the parser: as long as the slice is alive, the parser is still mutably borrowed. ## Why the loop fails with E0499 ```rust let mut p = HeaderParser::new(&buf); let mut lines = Vec::new(); while let Some(line) = p.next_line() { lines.push(line); } ``` Each `line` is pushed into `lines`, so it stays alive across iterations. With the elided signature, every live `line` keeps `p` mutably borrowed, and the next call to `p.next_line()` needs a second mutable borrow. rustc 1.99.1 reports **E0499** "cannot borrow `p` as mutable more than once at a time", labelled "`p` was mutably borrowed here in the previous iteration of the loop". Nothing about the bytes is wrong; the signature promised more than it needed to. ## The fix: return the struct's lifetime ```rust fn next_line(&mut self) -> Option<&'a [u8]> ``` Now the returned slice is tied to the buffer, not to the call. The `&mut self` borrow ends when the method returns, so the loop compiles, and the slices survive even `drop(p)`. A helper can build a parser, collect lines into a `Vec<&[u8]>` and return that vector after the parser is gone, because the lines borrow the caller's buffer. The body must actually produce an `&'a [u8]`. It does here because `self.src` is a shared reference: slicing through a `&'a [u8]` field yields data valid for `'a`, however short the `&mut self` borrow is. ## The same idea in the Iterator trait This is also why a borrowing iterator is written as `impl<'a> Iterator for HeaderParser<'a>` with `type Item = &'a [u8];`. `Iterator::next` takes `&mut self` and returns `Option<Self::Item>`, and the associated type cannot mention the `&mut self` borrow, so the item must be tied to the struct's own lifetime. Standard iterators such as `std::slice::Iter<'a, T>` follow the same shape, and it is what lets `collect()` gather every item into a `Vec` while the iterator keeps advancing. ## The mutable-field trap The same move does not work for a `&'a mut [u8]` field. A method like `fn next_chunk(&mut self, n: usize) -> &'a mut [u8]` that slices `self.buf` directly is rejected with "lifetime may not live long enough" (this error carries no E-code): handing out an `&'a mut` through a short `&mut self` could create two live mutable slices of the same bytes. The standard fix takes the field out first: 1. `let (head, tail) = std::mem::take(&mut self.buf).split_at_mut(n);` moves the `&'a mut [u8]` out, leaving an empty slice behind. 2. `self.buf = tail;` puts the remainder back. 3. `head` is returned with the full `'a`, and it can never overlap a later chunk. ## Borrowing struct fields separately A related surprise comes from getters. Given `fn headers(&self) -> &[String]` and `fn body_mut(&mut self) -> &mut Vec<u8>`, holding the headers slice while calling `body_mut()` fails with **E0502**: each method signature borrows the **whole** struct, and the borrow checker does not look inside the method bodies. Direct field access is checked per field, so `let hs = &req.headers; req.body.extend_from_slice(b"x");` compiles. When the fields are private, the options are: - a method that returns both parts at once, such as `fn parts_mut(&mut self) -> (&[String], &mut Vec<u8>)`; - splitting the struct so each part is its own value; - destructuring with `let Request { headers, body } = &mut req;` inside the module. ## Summary | Signature on `HeaderParser<'a>` | Result tied to | Collecting in a loop | |---|---|---| | `fn next_line(&mut self) -> Option<&[u8]>` | the `&mut self` call | E0499 | | `fn next_line(&mut self) -> Option<&'a [u8]>` | the buffer | Compiles | | `fn next_chunk(&mut self) -> &'a mut [u8]` slicing in place | the buffer, unsoundly | "lifetime may not live long enough" | | same, via `mem::take` then `split_at_mut` | the buffer | Compiles |
- Why can't `fn next_chunk(&mut self, n: usize) -> &'a mut [u8]` just slice `self.buf` when the field is `&'a mut [u8]`?Reborrowing through `&mut self` only yields data for that short borrow; returning it as `&'a mut` could leave two live mutable slices of the same bytes, so rustc says "lifetime may not live long enough". Move the field out with `std::mem::take(&mut self.buf)`, split it with `split_at_mut`, store the tail back and return the head.
- Why does holding the result of `req.headers()` block `req.body_mut()`, while `&req.headers` and `req.body` work together?A method signature borrows the whole struct, and the borrow checker does not look into method bodies, so the getters conflict with E0502. Direct field paths are tracked per field, so disjoint fields can be borrowed at once. Expose a method returning both parts, or destructure the struct.
- Elision ties a &mut self method's returned reference to the struct's lifetime parameter.
- The E0499 here means the parser is genuinely unsafe to call twice.
- Returning &'a [u8] means the line cannot outlive the parser.
- The borrow checker tracks which fields a getter method touches.
- Any &'a mut field can be handed out through &mut self like a shared one.