In Rust, why does rustc reject a `HeaderParser<'a>` used after its byte buffer is dropped, or built from `&read_request()`?
answer
- the struct is the borrow
- named local versus temporary
- end of the enclosing statement
- E0597 and E0716
basics
~20 sA struct holding a reference is itself a borrow of its source. Using it after a named buffer is dropped is E0597; building it from a temporary freed at the end of the let statement is E0716. Bind the bytes to a longer-lived local.
solid answer
~40 sA `HeaderParser<'a>` carries the borrow of the bytes it was built from, so rustc checks every later use against that buffer's owner. If the buffer is a local dropped in an inner block while the parser is used after it, rustc reports E0597 "`buf` does not live long enough". If it is built as `HeaderParser::new(&read_request())`, the `Vec<u8>` is a temporary freed at the end of the `let`, and a later use gives E0716 "temporary value dropped while borrowed"; rustc suggests binding it first. Two edges: `HeaderParser { src: &read_request(), pos: 0 }` compiles because a braced struct operand extends the temporary, and the borrow ends at the parser's last use unless the struct implements `Drop`. The fix is to make the owner outlive the parser, or to stop borrowing.
code
rust · 22 linesstruct HeaderParser<'a> {
src: &'a [u8],
pos: usize,
}
impl<'a> HeaderParser<'a> {
fn new(src: &'a [u8]) -> Self {
HeaderParser { src, pos: 0 }
}
fn rest(&self) -> &'a [u8] {
&self.src[self.pos..]
}
}
fn main() {
let parser;
{
let buf: Vec<u8> = b"Host: example.org\r\n".to_vec();
parser = HeaderParser::new(&buf);
} // `buf` is freed here
println!("{}", parser.rest().len());
}go deeper
Recall that a struct holding a reference cannot be used after the data it borrows is freed, and that binding the data to a local is the usual fix.
Distinguish E0597, a named local dropped too early, from E0716, a temporary freed at the end of the let, and explain where each owner dies.
Know the edges: temporary extension through braced struct expressions, borrows ending at last use, and how a Drop impl keeps a struct's borrow live to scope end.
When these errors keep recurring around one type, ask whether it should own its data instead of borrowing, rather than adding scopes around every caller.
## The struct carries the borrow A `HeaderParser<'a>` that stores `src: &'a [u8]` is, as far as the borrow checker is concerned, a borrow of whatever buffer it was built from. Every rule that applies to a bare `&[u8]` applies to the struct: it may not be used after the bytes are freed, and the bytes may not be moved or mutated while it is still used. The interesting part is *where* rustc decides the bytes are freed, because each way of losing the bytes produces its own error. ## Case 1: a named buffer dropped first (E0597) ```rust let parser; { let buf: Vec<u8> = b"Host: example.org\r\n".to_vec(); parser = HeaderParser::new(&buf); } // `buf` dropped here println!("{}", parser.rest().len()); ``` rustc 1.99.1 reports **E0597** "`buf` does not live long enough", with three labels: where `buf` is declared, "`buf` dropped here while still borrowed" at the closing brace, and "borrow later used here" on the `println!`. The struct is never mentioned as the culprit, because the borrow it carries is the one that outlives its owner. ## Case 2: a temporary freed at the end of the statement (E0716) ```rust let parser = HeaderParser::new(&read_request()); println!("{}", parser.rest().len()); ``` Here no named variable owns the `Vec<u8>`. `read_request()` returns a **temporary**, and a temporary is dropped at the end of the enclosing statement, the `let`. rustc reports **E0716** "temporary value dropped while borrowed" and suggests the fix itself: bind the result first, `let binding = read_request();`, then borrow `&binding`. The same error appears for `read_request().as_slice()` and `&read_request()[..]`: the owner is still a temporary. Two details sharpen the rule: - **Temporary lifetime extension.** `let parser = HeaderParser { src: &read_request(), pos: 0 };` compiles, because the operand of a braced struct expression in a `let` initializer is an *extending expression*, so the temporary lives to the end of the block. Arguments to function calls are not extending expressions, which is why the `HeaderParser::new(&read_request())` form fails. - **Using it inside one statement.** `HeaderParser::new(&read_request()).rest().len()` inside a single `println!` compiles: the temporary lives until that statement ends, and so does every use. ## When the borrow ends Under **non-lexical lifetimes**, which shipped with the 2018 edition, the borrow a struct carries lasts until the struct's **last use**, not until the closing brace of its scope. So `let p = HeaderParser::new(&buf); println!("{}", p.pos); drop(buf);` compiles. One exception matters for struct types: if `HeaderParser` implements `Drop`, its destructor may read the borrowed field, so the borrow stays live until the parser is dropped at scope end, and `drop(buf)` becomes E0505 "cannot move out of `buf` because it is borrowed". ## The outcomes side by side | Code shape | rustc 1.99.1 | |---|---| | Buffer local dropped in an inner block, parser used after | E0597 | | `HeaderParser::new(&read_request())`, parser used on a later line | E0716 | | `HeaderParser { src: &read_request(), pos: 0 }` in a `let` | Compiles (temporary extended) | | `let moved = buf;` while the parser is used later | E0505 | | `drop(buf)` after the parser's last use, no `Drop` impl | Compiles | | A function reads `buf` itself and returns `HeaderParser { src: &buf, .. }` | E0515 | The last row is the third face of the same rule. A function like `fn open_parser<'a>() -> HeaderParser<'a>` that reads the bytes into a local and returns a parser over them fails with **E0515** "cannot return value referencing local variable `buf`": the local is freed when the function returns, and no choice of `'a` by the caller can change that. Either the caller passes the buffer in, or the function returns something that owns it. ## Fixing it The repair is always to make the owner outlive the struct's uses, or stop borrowing: 1. Bind the data to a local in a scope at least as wide as the parser's uses. 2. Shorten the parser's life instead: finish with it inside the inner block, or consume it in one statement. 3. If the parser genuinely must outlive the buffer (stored in a cache, returned from the function that read the bytes), borrowing is the wrong design; give the struct owned data, which is a separate decision with its own costs. rustc's own help line for E0716, "consider using a `let` binding to create a longer lived value", is the first fix, and it is usually right. Wrapping the buffer in something clever does not help; the lifetime is a contract about who owns the bytes, and the fix is to arrange that ownership honestly.
- Why does `HeaderParser { src: &read_request(), pos: 0 }` compile when `HeaderParser::new(&read_request())` does not?In a `let` initializer, the operand of a braced struct expression is an extending expression, so rustc extends the temporary `Vec<u8>` to the end of the block. Function-call arguments are not extending expressions, so with `new` the temporary is freed at the end of the statement and a later use is E0716.
- Can the buffer be dropped while the parser variable is still in scope?Yes, after the parser's last use: non-lexical lifetimes end the borrow there, so `drop(buf)` compiles. If `HeaderParser` implements `Drop`, the destructor might read the field, so the borrow lasts until the parser drops at scope end and `drop(buf)` fails with E0505.
- The parser keeps the buffer alive because it holds a reference to it.
- E0597 and E0716 are the same error worded differently.
- A temporary always lives until the end of the enclosing block.
- The borrow inside a struct always lasts until the closing brace of its scope.
- Calling .as_slice() on the temporary avoids E0716.