A struct with a reference and 'static
Until now, references came into a function and went out of it. But you can also keep a reference, in a struct field.
A ticket, too, can be not only handed back but also put into a reader's folder. The folder with the ticket is valid no longer than the ticket itself: once the book is returned, the ticket in the folder leads nowhere.
Usually a struct's field owns its data: String, not &str. But a struct can also only look at someone else's text. Let's declare such a field as usual:
struct Excerpt {
part: &str, // ✗
}
fn main() {
let novel = String::from("Call me Ishmael. Some years ago");
let e = Excerpt { part: &novel[..15] };
println!("{}", e.part);
}error[E0106]: missing lifetime specifierThe same error as longest without an annotation. The elision rules do not apply to struct fields: a reference field always has its lifetime written out.
A field with a lifetime
struct Excerpt<'a> {
part: &'a str,
}
fn main() {
let novel = String::from("Call me Ishmael. Some years ago");
let e = Excerpt { part: &novel[..15] };
println!("{}", e.part); // Call me Ishmael
}Let's take the declaration apart:
struct Excerpt<'a>declares a lifetime parameter on the struct, as<T>does on a generic type.part: &'a strsays the field is a reference valid on the stretch'a.- Together it reads: an
Excerptvalue cannot outlive the textpartlooks at.
In main, the field part looks at the first 15 bytes of the string novel. If you declare e outside a block, novel inside it, and print e.part after the block, the compiler answers error[E0597]: `novel` does not live long enough. A struct holding a reference is that folder with a ticket: it cannot be valid longer than the book.
The 'static lifetime
'static is the only lifetime with a ready-made name. A &'static str reference is valid until the program ends. Every string literal has this type: its bytes are built into the program itself and are never freed.
fn greeting() -> &'static str {
"hello"
}
fn main() {
let s: &'static str = "world";
println!("{} {s}", greeting()); // hello world
}greeting has no reference parameters, so the elision rules have nowhere to take the result's lifetime from. Here 'static tells the truth: the function returns a literal that lives for the whole program. The variable s has the same type written out, though the compiler would infer it by itself.
This is where the library picture stops being accurate: a library has no tickets valid forever. And a literal has no owner to take it away: its bytes are built into the program at build time and stay in memory while it runs.
Common mistake
To return a reference to a string built inside a function, someone adds 'static:
fn label(n: i32) -> &'static str {
let s = format!("id-{n}");
&s // ✗
}
fn main() {
println!("{}", label(7));
}error[E0515]: cannot return reference to local variable `s`'static does not extend the life of the string s: it is still freed at the function's }. The annotation only demands what is not there, and the compiler refuses. The fix is to return the string itself: the result type String and format!("id-{n}") as the last line.
Key points
- A reference field needs a lifetime,
struct Excerpt<'a> { part: &'a str }: the elision rules do not apply to fields. - A struct holding a reference cannot outlive the data it looks at (E0597).
&'static stris valid until the program ends, like a literal;'staticdoes not extend the life of a local string.