Skip to content

Rust shouldn't suggest using a single lifetime everywhere #148315

@theemathas

Description

@theemathas

Code

pub fn foo(x: &i32, y: &i32) -> &i32 {
    x
}

Current output

error[E0106]: missing lifetime specifier
 --> src/lib.rs:1:33
  |
1 | pub fn foo(x: &i32, y: &i32) -> &i32 {
  |               ----     ----     ^ expected named lifetime parameter
  |
  = help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `x` or `y`
help: consider introducing a named lifetime parameter
  |
1 | pub fn foo<'a>(x: &'a i32, y: &'a i32) -> &'a i32 {
  |           ++++     ++          ++          ++

For more information about this error, try `rustc --explain E0106`.

Desired output

...
pub fn foo<'a>(x: &'a i32, y: &i32) -> &'a i32 {
...

Rationale and extra context

The compiler is telling the user to apply the same lifetime everywhere. This is incorrect, and will make the code seemingly work, but then will fail later.

This issue of incorrectly using a single lifetime everywhere is a very common beginner pitfall, and the compiler teaching that to users does not help.

Other cases

Rust Version

Reproducible on the playground with version 1.93.0-nightly
(2025-10-29 292be5c7c05138d753bb)

Anything else?

Ideally, the compiler should be able to look at the function body to determine how to correctly annotate the lifetime. But if that's not feasible, the compiler should at least suggest annotating the lifetime only one time, with each possible place as alternatives in the suggestion.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-lifetimesArea: Lifetimes / regionsD-invalid-suggestionDiagnostics: A structured suggestion resulting in incorrect code.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