Skip to content

Don't suggest adding 'static lifetime to function arguments #69350

Closed

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".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsC-enhancementCategory: An issue proposing an enhancement or a PR with one.D-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions