The two meanings of ‘static, what T: ‘a says, why Box of dyn Trait means ‘static, structs that need two lifetimes, and how to read E0716, E0521 and E0505 line by line.
Part 9 showed what 'a means in a function signature, the elision rules, and structs that hold a reference. This part picks up the harder cases: the two different things 'static can mean, bounds like T: 'a, lifetimes on trait objects, and structs that need two lifetimes instead of one.
The second half is about reading the errors you’ll meet when these go wrong. We take three real ones apart line by line, and then look at when to stop fighting the borrow checker and change the design. Every program here was run on Rust 1.95, and its output is pasted from the run.
Try this first
keep_forever asks for a type T: 'static. We call it twice: once with an owned String, once with a reference to one. Which call does the compiler reject?
use std::fmt::Debug;
fn keep_forever<T: Debug + 'static>(item: T) {
println!("keeping {item:?}");
}
fn main() {
let owned = String::from("owned text");
keep_forever(owned);
let local = String::from("borrowed text");
keep_forever(&local);
}
It prints:
error[E0597]: `local` does not live long enough
--> src/main.rs:12:18
|
11 | let local = String::from("borrowed text");
| ----- binding `local` declared here
12 | keep_forever(&local);
| -------------^^^^^^-
| | |
| | borrowed value does not live long enough
| argument requires that `local` is borrowed for `'static`
13 | }
| - `local` dropped here while still borrowed
|
note: requirement that the value outlives `'static` introduced here
--> src/main.rs:3:28
|
3 | fn keep_forever<T: Debug + 'static>(item: T) {
| ^^^^^^^
Most people guess the opposite. A String made in main clearly doesn’t live for the whole program, so how can it be 'static? But the compiler accepts line 9 and rejects line 12. The note: points at the bound that caused it. To see why, we need to split 'static into its two meanings.
Two meanings of ‘static
&'static T: a reference that’s good until the program ends
When 'static sits on a reference, it means what it sounds like. The value behind &'static T lives until the program exits, so the reference can be used anywhere, at any time. There are three common ways to get one:
static GREETING: &str = "hello";
static LIMITS: [u32; 3] = [10, 100, 1000];
fn make_name(n: u32) -> &'static str {
let s = format!("worker-{n}");
Box::leak(s.into_boxed_str())
}
fn main() {
let literal: &'static str = "a literal";
let limit: &'static u32 = &LIMITS[1];
let name = make_name(7);
println!("{GREETING}, {literal}, {limit}, {name}");
}
It prints:
hello, a literal, 100, worker-7
- String literals are stored in the program file itself, as Part 9 showed.
- A
staticitem is one value with a fixed place in memory for the whole run.GREETINGandLIMITSare statics, so&LIMITS[1]is a&'static u32. Box::leaktakes a value on the heap and gives up ownership of it on purpose. Nobody owns it any more, so nobody drops it, and the memory stays until the program exits. Part 20 coveredBox.into_boxed_strturns theStringinto aBox<str>, which is a string on the heap with no spare capacity.
Every Box::leak call leaks memory for good. It suits a few values made once at start-up, like a config that every thread reads. In a loop, it’s a memory leak.
T: 'static: a type that holds no short borrows
When 'static is a bound on a type, as in T: 'static, it means something else. It says: values of type T don’t borrow anything that could go away first. It doesn’t say the value lives forever. It says the value could be kept as long as you like, because nothing inside it can dangle.
An owned type always passes this test. A String owns its bytes, and a Vec<i32> owns its numbers. Neither points at anybody else’s data, so keeping them longer can’t create a dangling reference. A &'static str passes too, since what it points at never goes away. A &String borrowed from a local variable fails, because the local will be dropped at the end of its scope.
So in “Try this first”, T was String in the first call, an owned type, and it passed. In the second call, T was &String, a borrow of local, which is dropped at the end of main. So it failed.
| You write | It means | Example |
|---|---|---|
&'static T |
a reference whose target lives until the program ends | "hello", &LIMITS[1], Box::leak(...) |
T: 'static |
T holds no borrow that could end first |
String, Vec<i32>, &'static str |
Why would a function ask for T: 'static? Because it plans to keep the value for an unknown time. std::thread::spawn is the famous one. A new thread can outlive the function that started it, so everything the thread’s closure holds must be 'static. Part 23 showed this. The usual fix there is to move owned data into the thread, which is exactly what the bound allows.
T: ‘a: what’s inside T must outlive ‘a
T: 'static is one case of a general bound, T: 'a. Read it as: every borrow inside T lives at least as long as 'a. If T owns everything, it passes for any 'a. If T is &'b str, it passes only if 'b lasts at least as long as 'a.
You’ve already relied on this without writing it. Take a struct that holds a reference to some T: struct Holder<'a, T> { item: &'a T }.
For the &'a T to be safe, the T it points at must not hold any borrow that ends before 'a does. Otherwise you’d have a good reference to a value with a dangling one inside it. So &'a T implies T: 'a. The compiler works this out from the field type, so you don’t write it. Code from before 2018 writes struct Holder<'a, T: 'a>, which means the same thing.
You do need to write it when the compiler can’t see it from a reference. The common case is a trait object. Here’s a function that puts any Display value in a box:
use std::fmt::Display;
fn boxed<T: Display>(x: T) -> Box<dyn Display> {
Box::new(x)
}
fn main() {
println!("{}", boxed(5));
}
It prints:
error[E0310]: the parameter type `T` may not live long enough
--> src/main.rs:4:5
|
3 | fn boxed<T: Display>(x: T) -> Box<dyn Display> {
| ----------- this `dyn Trait` has an implicit `'static` lifetime bound
4 | Box::new(x)
| ^^^^^^^^^^^
| |
| the parameter type `T` must be valid for the static lifetime...
| ...so that the type `T` will meet its required lifetime bounds
|
help: consider adding an explicit lifetime bound
|
3 | fn boxed<T: Display + 'static>(x: T) -> Box<dyn Display> {
| +++++++++
The first label is the surprise: Box<dyn Display> has an implicit 'static bound. The next section is about that. The help: offers T: 'static, which works if you’ll only box owned values. If you want to box borrows too, name a lifetime and tie both sides to it:
use std::fmt::Display;
fn boxed<'a, T: Display + 'a>(x: T) -> Box<dyn Display + 'a> {
Box::new(x)
}
fn main() {
let name = String::from("Ana");
let items: Vec<Box<dyn Display + '_>> = vec![boxed(5), boxed("text"), boxed(&name)];
for item in &items {
println!("{item}");
}
}
It prints:
5
text
Ana
T: Display + 'a says “T implements Display, and its borrows last at least 'a“. Box<dyn Display + 'a> says “this box may hold borrows that last 'a, no longer”. The two match, so the compiler accepts the Box::new. In main, '_ lets the compiler pick 'a; the next sections cover '_.
Box<dyn Trait> means Box<dyn Trait + 'static>
Part 21 introduced trait objects: dyn Trait is “some type that implements Trait, chosen at run time”, and it lives behind a pointer like Box. A trait object hides the real type, so the compiler can’t look inside it to find its borrows. It needs to be told how long they last, and it uses a default when you don’t say.
For Box<dyn Trait> with no lifetime written, the default is 'static. Behind a reference it’s different: &'a dyn Trait defaults to &'a (dyn Trait + 'a), so a borrowed trait object may hold borrows as long as the reference itself. Here’s where that bites. A Menu holds a list of actions, each a boxed closure (Part 16):
struct Menu {
actions: Vec<Box<dyn Fn() -> String>>,
}
fn main() {
let mut menu = Menu {
actions: Vec::new(),
};
let name = String::from("Ana");
menu.actions.push(Box::new(|| format!("hello, {name}")));
for a in &menu.actions {
println!("{}", a());
}
}
It prints:
error[E0597]: `name` does not live long enough
...
| | | borrowed value does not live long enough
| | value captured here
| coercion requires that `name` is borrowed for `'static`
...
= note: due to object lifetime defaults, `Box<dyn Fn() -> String>` actually means `Box<(dyn Fn() -> String + 'static)>`
The closure borrows name. Turning it into a Box<dyn Fn() -> String> (the “coercion”) requires that borrow to be 'static, and it isn’t. The note: says the rule out loud. Two fixes, and you pick by asking who should own name.
If the menu may borrow from its surroundings, give it a lifetime parameter and put it on the trait object:
struct Menu<'a> {
actions: Vec<Box<dyn Fn() -> String + 'a>>,
}
fn main() {
let name = String::from("Ana");
let mut menu = Menu {
actions: Vec::new(),
};
menu.actions.push(Box::new(|| format!("hello, {name}")));
menu.actions.push(Box::new(|| format!("bye, {name}")));
for action in &menu.actions {
println!("{}", action());
}
}
It prints:
hello, Ana
bye, Ana
name is now declared before menu. Values are dropped in reverse order (Part 6), so menu and its closures go first, while name is still alive.
If the menu should stand on its own, keep Menu as it was and make each closure own a copy with move: let n = name.clone();, then Box::new(move || format!("hello, {n}")). The closures then hold no borrows, so they pass 'static, and the menu can be returned from a function or kept as long as you like.
impl Trait and ‘_
Return-position impl Trait (Part 15) is the other way to return “something that implements a trait”. Here’s a function that returns an iterator over a borrowed slice:
fn evens(v: &[i32]) -> impl Iterator<Item = i32> {
v.iter().copied().filter(|n| n % 2 == 0)
}
fn long_words(text: &str, min: usize) -> impl Iterator<Item = &str> + '_ {
text.split(' ').filter(move |w| w.len() >= min)
}
fn main() {
let numbers = [1, 2, 3, 4, 5, 6];
let e: Vec<i32> = evens(&numbers).collect();
println!("{e:?}");
let text = String::from("a quick brown fox jumps");
let words: Vec<&str> = long_words(&text, 5).collect();
println!("{words:?}");
}
It prints:
[2, 4, 6]
["quick", "brown", "jumps"]
The iterator evens returns borrows v, but the signature doesn’t say so. In edition 2024, which this series uses, that’s fine: a returned impl Trait may borrow from every lifetime in the signature. In the 2021 edition, evens fails with E0700 (“hidden type … captures lifetime that does not appear in bounds”), and the fix was + '_, as on long_words. You’ll see + '_ in older code. In edition 2024 it’s harmless and not needed.
The ‘_ placeholder
'_ has turned up several times now. It’s the anonymous lifetime: “the compiler picks this, by the usual rules”. It saves inventing a name you’d use once. You’ve seen it in a return type that borrows, Excerpt<'_> (Part 9), and on a trait object, Box<dyn Display + '_>. The next worked examples use it in an impl block, impl Finder<'t, '_>, for a lifetime the methods never mention.
Worked example: a word reader whose words outlive it
Methods follow elision rule 3 from Part 9: if a method takes &self or &mut self, every returned reference gets the lifetime of self. Usually that’s what you want. Here it isn’t. Words holds a borrowed &str and hands out one word at a time:
struct Words<'a> {
rest: &'a str,
}
impl<'a> Words<'a> {
fn new(text: &'a str) -> Self {
Words { rest: text }
}
fn next_word(&mut self) -> Option<&str> {
let text = self.rest.trim_start();
if text.is_empty() {
return None;
}
let end = text.find(' ').unwrap_or(text.len());
let (word, rest) = text.split_at(end);
self.rest = rest;
Some(word)
}
}
fn main() {
let line = String::from("the quick brown fox");
let mut words = Words::new(&line);
let first = words.next_word();
let second = words.next_word();
println!("{first:?} {second:?}");
}
It prints:
error[E0499]: cannot borrow `words` as mutable more than once at a time
--> src/main.rs:26:18
|
25 | let first = words.next_word();
| ----- first mutable borrow occurs here
26 | let second = words.next_word();
| ^^^^^ second mutable borrow occurs here
27 | println!("{first:?} {second:?}");
| ----- first borrow later used here
impl<'a> Words<'a> declares 'a once for the whole block, so every method can name it. next_word takes &mut self and returns Option<&str>. By rule 3, the &str gets the lifetime of that &mut self borrow, so the compiler treats the word as borrowed from words itself. While first is alive, words stays mutably borrowed, and E0499 (Part 7) forbids a second &mut.
But the word doesn’t point into words. It points into line, through self.rest, which is a &'a str. The signature ties it to the wrong thing, the same mistake as value_of in Part 9. Say where it really comes from:
struct Words<'a> {
rest: &'a str,
}
impl<'a> Words<'a> {
fn new(text: &'a str) -> Self {
Words { rest: text }
}
fn next_word(&mut self) -> Option<&'a str> {
let text = self.rest.trim_start();
if text.is_empty() {
return None;
}
let end = text.find(' ').unwrap_or(text.len());
let (word, rest) = text.split_at(end);
self.rest = rest;
Some(word)
}
}
fn main() {
let line = String::from("the quick brown fox");
let mut words = Words::new(&line);
let first = words.next_word();
let second = words.next_word();
println!("{first:?} {second:?}");
}
It prints:
Some("the") Some("quick")
Option<&'a str> says the word lives as long as the text, not as long as this call’s borrow of words. The &mut self borrow now ends when next_word returns. The body still has to keep the promise: word is a slice of self.rest, which is &'a str, so it is.
The rule of thumb for methods: return &'a T when the result comes from data the struct borrows, and let elision give you &self‘s lifetime when it comes from data the struct owns.
Worked example: when one lifetime isn’t enough
A Finder holds a text and a word to look for. It returns the first line that contains the word. With a single 'a for both fields:
struct Finder<'a> {
text: &'a str,
word: &'a str,
}
impl<'a> Finder<'a> {
fn line_with_word(&self) -> Option<&'a str> {
self.text.lines().find(|line| line.contains(self.word))
}
}
fn main() {
let poem = String::from("roses are red\nviolets are blue\nsugar is sweet");
let found;
{
let typed = "BLUE".to_lowercase();
let finder = Finder {
text: &poem,
word: &typed,
};
found = finder.line_with_word();
}
println!("{found:?}");
}
It prints:
error[E0597]: `typed` does not live long enough
--> src/main.rs:19:19
|
16 | let typed = "BLUE".to_lowercase();
| ----- binding `typed` declared here
...
19 | word: &typed,
| ^^^^^^ borrowed value does not live long enough
...
22 | }
| - `typed` dropped here while still borrowed
23 | println!("{found:?}");
| ----- borrow later used here
Read it bottom up. found is used on line 23. Its type is Option<&'a str>, so 'a must reach line 23. One 'a covers both fields, so typed must also live until line 23. It’s dropped on line 22.
With one name for two borrows, the compiler picks a single stretch that fits both. &poem could last longer, but a long-lived reference can always be used as a shorter one, so it’s shrunk to match &typed. (“A longer lifetime can stand in for a shorter one” is called subtyping, and the rules for how it carries through types like &'a T are called variance; we won’t need more of either.) The result gets that shorter stretch.
Give each field its own lifetime, and tie the result to the text only:
struct Finder<'t, 'w> {
text: &'t str,
word: &'w str,
}
impl<'t> Finder<'t, '_> {
fn line_with_word(&self) -> Option<&'t str> {
self.text.lines().find(|line| line.contains(self.word))
}
}
fn main() {
let poem = String::from("roses are red\nviolets are blue\nsugar is sweet");
let found;
{
let typed = "BLUE".to_lowercase();
let finder = Finder {
text: &poem,
word: &typed,
};
found = finder.line_with_word();
}
println!("{found:?}");
}
It prints:
Some("violets are blue")
't and 'w are separate now, so 't can be as long as poem while 'w stays as short as typed. The method’s result mentions only 't, so the impl block names 't and writes '_ for the other.
Start with one lifetime. Add a second only when a caller hits an error like this one, where a short borrow is dragging down a long one.
Reading the hard errors
Borrow-checker errors all have the same parts. Once you know where each part sits, a long error reads in a few seconds. Here’s one, labelled.
A real E0716 error, labelled. The code and summary come first, then where the problem is, then the source with ^ under the main spot and – under the places that explain it, then a suggested fix.
In words, from the top:
error[E0716]:and a summary. The code is the thing to search for.rustc --explain E0716prints a full page with examples.-->and a location.src/main.rs:6:16is file, line 6, column 16. It points at the main spot.^labels mark the main spot. There’s usually one.-labels mark other places that are part of the story: where a borrow starts, where a value is dropped, where a borrow is used later. Read them in line order and they tell what happened in time.help:suggests a change, shown as a diff:~marks a changed line and+marks added text. Anote:line, when there is one, adds a fact, like the object lifetime default we saw forBox<dyn Fn>.
Now three errors you’ll meet often, each read with this map.
E0716: temporary value dropped while borrowed
Here’s the figure’s program. Its error is the text in the figure.
fn read_name() -> String {
String::from(" Ada ")
}
fn main() {
let name = read_name().trim();
println!("hello, {name}");
}
It prints:
error[E0716]: temporary value dropped while borrowed
--> src/main.rs:6:16
|
6 | let name = read_name().trim();
| ^^^^^^^^^^^ - temporary value is freed at the end of this statement
| |
| creates a temporary value which is freed while still in use
7 | println!("hello, {name}");
| ---- borrow later used here
|
help: consider using a `let` binding to create a longer lived value
|
6 ~ let binding = read_name();
7 ~ let name = binding.trim();
|
read_name() returns a String, and nothing owns it: it isn’t stored in a variable. A value like that is a temporary, and Rust drops it at the end of the statement, the ; marked with -. trim returns a &str that points into it. Line 7 uses that &str after the temporary is gone.
The help: is right: give the String an owner that lives long enough.
fn read_name() -> String {
String::from(" Ada ")
}
fn main() {
let line = read_name();
let name = line.trim();
println!("hello, {name}");
}
It prints:
hello, Ada
The other fix is to own the result: let name = read_name().trim().to_string();. That makes a new String from the trimmed text, so the temporary can go.
E0521: borrowed data escapes outside of function
This function starts a thread that prints a message. Remember from Part 23 that a spawned thread may still be running after this function has returned.
use std::thread;
fn print_later(msg: &str) -> thread::JoinHandle<()> {
thread::spawn(move || println!("{msg}"))
}
fn main() {
let text = String::from("hello from a thread");
print_later(&text).join().unwrap();
}
It prints:
error[E0521]: borrowed data escapes outside of function
--> src/main.rs:4:5
|
3 | fn print_later(msg: &str) -> thread::JoinHandle<()> {
| --- - let's call the lifetime of this reference `'1`
| |
| `msg` is a reference that is only valid in the function body
4 | thread::spawn(move || println!("{msg}"))
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| |
| `msg` escapes the function body here
| argument requires that `'1` must outlive `'static`
On line 3, the compiler invents a name, '1, for the lifetime of msg, because you never named it. Then it says msg is only valid in the function body: the caller may drop the text as soon as print_later returns.
Line 4 finishes the story. The closure holding msg goes to thread::spawn, which needs T: 'static. So '1 would have to outlive 'static, and nothing borrowed from a caller can promise that.
main happens to wait with join, but the compiler checks print_later on its own, from its signature. Move owned data into the thread instead:
use std::thread;
fn print_later(msg: &str) -> thread::JoinHandle<()> {
let msg = msg.to_string();
thread::spawn(move || println!("{msg}"))
}
fn main() {
let text = String::from("hello from a thread");
print_later(&text).join().unwrap();
}
It prints:
hello from a thread
The closure now owns a String, which passes T: 'static. Part 23 showed the other fix, scoped threads, which are allowed to borrow because they must finish before the scope ends.
E0505: cannot move out because it is borrowed
We want a Library that keeps its books and a reference to the favourite one:
struct Library<'a> {
books: Vec<String>,
favourite: &'a str,
}
fn main() {
let books = vec![String::from("Dune"), String::from("Emma")];
let favourite = &books[1];
let lib = Library { books, favourite };
println!("{} books, favourite {}", lib.books.len(), lib.favourite);
}
It prints:
error[E0505]: cannot move out of `books` because it is borrowed
--> src/main.rs:9:25
|
7 | let books = vec![String::from("Dune"), String::from("Emma")];
| ----- binding `books` declared here
8 | let favourite = &books[1];
| ----- borrow of `books` occurs here
9 | let lib = Library { books, favourite };
| ^^^^^ --------- borrow later used here
| |
| move out of `books` occurs here
|
help: consider cloning the value if the performance cost is acceptable
|
8 | let favourite = &books.clone()[1];
| ++++++++
Read the - labels in line order: books is declared (7), borrowed (8), and the borrow is used later (9). The ^ is the move in between. Rust doesn’t let you move a value while a borrow of it is still in use. After the move, the new owner could change or drop the Vec, and favourite would point at freed memory. (Here the heap buffer would happen to stay where it is, but the rule doesn’t look that closely.)
The help: clones the whole Vec so that favourite has a copy to point at. That compiles, but it makes a second list that exists only to be pointed at. The real problem is the design: a struct that points into its own field. Rust has no safe way to write that with plain references. It’s time to stop fighting.
When to stop fighting
If you’ve added lifetimes twice and the error has only moved, the data probably wants a different shape. These four changes fix most cases, from cheapest to think about to most structured:
- Clone a small value. Cloning a short
Stringto get past an error is fine. Measure before you worry about it. - Own the data. A struct with
Stringfields instead of&strfields has no lifetime parameter at all, and can go anywhere. - Store an index, not a reference. Point at an item by its position, and look it up when needed.
- Share ownership with
Rc(Part 20) when several places need the same value and none of them is clearly the owner.
Here’s Library with an index:
struct Library {
books: Vec<String>,
favourite: usize,
}
impl Library {
fn favourite(&self) -> &str {
&self.books[self.favourite]
}
}
fn main() {
let books = vec![String::from("Dune"), String::from("Emma")];
let lib = Library {
books,
favourite: 1,
};
println!("{} books, favourite {}", lib.books.len(), lib.favourite());
}
It prints:
2 books, favourite Emma
Library has no lifetime parameter now. The method borrows from &self when it’s called, which elision handles. The price is that an index can go stale: remove a book, and favourite may point at the wrong one, or past the end. A reference could never do that.
The Rc version stores books: Vec<Rc<str>> and favourite: Rc<str>, and sets favourite to Rc::clone(&books[1]). Both then share ownership of the same text, so removing a book from the list can’t leave favourite dangling or pointing at the wrong book.
Tips and traps
- Reading
T: 'staticas “lives forever”. It means “holds no short borrows”. An ownedStringmade a moment ago passes. When a function asks forT: 'static, give it owned data, often with.to_string()or.clone()before amove. - Forgetting that
Box<dyn Trait>means+ 'static. The error mentions'staticor “coercion requires”, and thenote:names “object lifetime defaults”. Add a lifetime (Box<dyn Trait + 'a>) if it should borrow, or make the closure own its data if it shouldn’t. - A method that ties its result to
&mut self. Calling it twice gives E0499, even though the results point elsewhere. Return&'a Twhen the result comes from data the struct borrows. - One lifetime for two unrelated references. A short borrow drags the long one down, and the result can’t outlive the short one. Give each field its own lifetime and tie the result only to the one it comes from.
- Calling a method on a function’s result and keeping the borrow.
read_name().trim()gives E0716. Store the value in aletfirst, or own the result with.to_string(). - Following every
help:line. They’re usually right, but not always the best design. In E0505, cloning the wholeVeccompiled but hid a struct that pointed into itself.
&'static Tpoints at something that never goes away.T: 'staticonly meansTborrows nothing that could.
Exercises
Exercise 1. Without running it, decide which of these five types pass T: 'static: String, &'static str, Vec<&'static str>, Box<dyn std::fmt::Display>, and &String where the String is a local variable in main.
Exercise 2. This program fails with E0716. Fix it so it prints 3 words, first is apple.
fn read_line() -> String {
String::from(" apple banana cherry ")
}
fn main() {
let words: Vec<&str> = read_line().trim().split(' ').collect();
println!("{} words, first is {}", words.len(), words[0]);
}
It prints:
error[E0716]: temporary value dropped while borrowed
Exercise 3. This function doesn’t compile. Fix it two ways: once by keeping the &str parameter and changing the return type, and once by making the closure own its data. Both should print hello, Ana.
fn make_greeter(name: &str) -> Box<dyn Fn() -> String> {
Box::new(move || format!("hello, {name}"))
}
fn main() {
let g = make_greeter("Ana");
println!("{}", g());
}
It prints:
error: lifetime may not live long enough
...
2 | Box::new(move || format!("hello, {name}"))
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ returning this value requires that `'1` must outlive `'static`
This error has no code. Some borrow-checker errors don’t, and you read them the same way.
Answers
1. Four of them pass. String owns its bytes. &'static str points at text that never goes away. Vec<&'static str> owns a list of such references. Box<dyn Display> is really Box<dyn Display + 'static>, so whatever it holds passes by definition. Only the &String fails, because the local is dropped at the end of main:
use std::fmt::Display;
fn check<T: 'static>(_: &T) -> &'static str {
"passes"
}
fn main() {
let owned = String::from("hi");
let names: Vec<&'static str> = vec!["Ana"];
let shown: Box<dyn Display> = Box::new(5);
println!("String: {}", check(&owned));
println!("&'static str: {}", check(&"lit"));
println!("Vec<&'static str>: {}", check(&names));
println!("Box<dyn Display>: {}", check(&shown));
}
It prints:
String: passes
&'static str: passes
Vec<&'static str>: passes
Box<dyn Display>: passes
2. The String from read_line() is a temporary, dropped at the ;, and words points into it. Give it an owner:
fn read_line() -> String {
String::from(" apple banana cherry ")
}
fn main() {
let line = read_line();
let words: Vec<&str> = line.trim().split(' ').collect();
println!("{} words, first is {}", words.len(), words[0]);
}
It prints:
3 words, first is apple
3. The return type Box<dyn Fn() -> String> means + 'static, but the closure holds a &str from the caller. Either say the box may borrow it, with + '_, which is what the full error’s help: line suggests, or give the closure its own String:
fn greeter_borrowing(name: &str) -> Box<dyn Fn() -> String + '_> {
Box::new(move || format!("hello, {name}"))
}
fn greeter_owning(name: &str) -> Box<dyn Fn() -> String> {
let name = name.to_string();
Box::new(move || format!("hello, {name}"))
}
fn main() {
let a = greeter_borrowing("Ana");
let b = greeter_owning("Ana");
println!("{}", a());
println!("{}", b());
}
It prints:
hello, Ana
hello, Ana
The first can’t outlive the &str it was given. The second can go anywhere, including into a thread.
What’s next
Threads let a program do several things at once by giving each its own stack. In Part 26, we’ll do the same with one thread and many small tasks: the Future trait, poll and Waker, a tiny executor built by hand, and then the same program on tokio.