Rust: Suggest named lifetime on trait functions like we do for free functions

Created on 1 Jul 2020  路  11Comments  路  Source: rust-lang/rust

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> {
  |       ^^^^    ^^^^^^^     ^^^^^^^            ^^^



md5-07118115eacc94990369af2b01a884fd



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


This issue has been assigned to @schuermannator via this comment.


A-diagnostics A-suggestion-diagnostics C-enhancement D-newcomer-roadblock E-easy T-compiler

Most helpful comment

@rustbot claim

All 11 comments

@rustbot claim

@schuermannator Are you still working on this?

Well, yes. I actually just pinged the Zulip chat on yesterday for some help. Just spent a while trying to get up to speed on everything. Have you worked on it some or are you interested?

I haven't worked on it, was just interested. I won't step on your toes.

Is this still being actively worked on? If not, can I give it a try?

yea please do! I haven't had the bandwidth - just haven't really gotten it off the ground. I'm happy to help! let me know if you get the ball rolling on this

Thanks! I'll ping people on Zulip

@schuermannator what's the best way to reach you? would love to talk more about this :)

I'm on the Rust discord/zulip! (zachschuermann/Zach Schuermann resp.)

Changed issue title to be clearer:

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

Hey @estebank, @schuermannator and I both looked into this, but found that the error reporting for traits and free functions live in different modules. Moreover, add_missing_lifetime_specifiers_label is an instance method and doesn't seem to fit in naturally in different_lifetimes.rs. Do you have any suggestions on this?

Was this page helpful?
0 / 5 - 0 ratings