Description
When using a temporary reference in a context where temporary references are not allowed, rustc gives a technically-correct suggestion that in practice is most often misleading and makes beginners stuck trying to solve a wrong problem:
fn naninani(arg: &str) {
std::thread::spawn(|| {
println!("{}", arg);
});
}
error[E0621]: explicit lifetime required in the type of `arg`
--> src/lib.rs:2:5
|
1 | fn naninani(arg: &str) {
| ---- help: add explicit lifetime `'static` to the type of `arg`: `&'static str`
2 | std::thread::spawn(|| {
| ^^^^^^^^^^^^^^^^^^ lifetime `'static` required
This suggestion is very unlikely to be useful in a real program. If the function is changed to require arguments with a 'static
lifetime, it generally just causes more borrow checking errors at the call sites of the function, causing inexperienced users dig deeper in the wrong direction.
My suggestions:
-
Don't make code change suggestions for
'static
lifetime outside of globals. In this case no suggestion at all would be better than a misleading code change. -
Because the correct solution is most likely not to use a reference at all, don't focus the message on the (unusual) kind of reference that would work, but explain that most (i.e. non-
'static
) references won't work.
I suggest changing "lifetime 'static
required" say something along the lines of "temporary references are not allowed".