-
Notifications
You must be signed in to change notification settings - Fork 13.9k
Open
Labels
A-diagnosticsArea: Messages for errors, warnings, and lintsArea: Messages for errors, warnings, and lintsA-lifetimesArea: Lifetimes / regionsArea: Lifetimes / regionsD-invalid-suggestionDiagnostics: A structured suggestion resulting in incorrect code.Diagnostics: A structured suggestion resulting in incorrect code.D-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.Diagnostics: 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.Relevant to the compiler team, which will review and decide on the PR/issue.
Description
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.
suprohub and lolbinarycat
Metadata
Metadata
Assignees
Labels
A-diagnosticsArea: Messages for errors, warnings, and lintsArea: Messages for errors, warnings, and lintsA-lifetimesArea: Lifetimes / regionsArea: Lifetimes / regionsD-invalid-suggestionDiagnostics: A structured suggestion resulting in incorrect code.Diagnostics: A structured suggestion resulting in incorrect code.D-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.Diagnostics: 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.Relevant to the compiler team, which will review and decide on the PR/issue.