Skip to content

Suggest named lifetime on trait functions like we do for free functions #73931

Closed
@estebank

Description

@estebank

The following fn foo provides a structured suggestion to add a new named lifetime:

fn foo(x: &i32, y: &i32) -> Option<&i32> {
    Some(y)
}
error[E0106]: missing lifetime specifier
 --> src/lib.rs:1:36
  |
1 | fn foo(x: &i32, y: &i32) -> Option<&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 | fn foo<'a>(x: &'a i32, y: &'a i32) -> Option<&'a i32> {
  |       ^^^^    ^^^^^^^     ^^^^^^^            ^^^

But similar code in a trait, doesn't:

trait T {
    fn foo(&self, x: &i32, y: &i32) -> Option<&i32> {
        Some(y)
    }
}
error[E0623]: lifetime mismatch
 --> src/lib.rs:3:9
  |
2 |     fn foo(&self, x: &i32, y: &i32) -> Option<&i32> {
  |                               ----     ------------
  |                               |
  |                               this parameter and the return type are declared with different lifetimes...
3 |         Some(y)
  |         ^^^^^^^ ...but data from `y` is returned here

The method add_missing_lifetime_specifiers_label is the one responsible for the former suggestion and can probably be easily reused where the method lifetime issue is emitted.

Thanks to https://users.rust-lang.org/t/this-parameter-and-the-return-type-are-declared-with-different-lifetimes/45200 for making me notice this discrepancy.

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`C-enhancementCategory: An issue proposing an enhancement or a PR with one.D-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.E-easyCall for participation: Easy difficulty. Experience needed to fix: Not much. Good first issue.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