Skip to content

Error messages suggest lifetime annotations for stack references in some cases (E 106 instead of E 515) #77965

@skade

Description

@skade

In a training, I was presented with the following code that someone wrote:

struct Point {
    x: i32,
    y: i32,
}

fn x_diff(a: &Point, b: &Point) -> &i32 {
    let diff = b.x - a.x;
    return &diff;
}

fn main() {
    let a = Point{ x: 1, y: 2 };
    let b = Point{ x: 3, y: 4 };
    let c = x_diff(&a, &b);
}

I expected to see this happen:

error[E0515]: cannot return reference to local variable `diff`
 --> src/main.rs:8:12
  |
8 |     return &diff;
  |            ^^^^^ returns a reference to data owned by the current function

Instead, this happened:

error[E0106]: missing lifetime specifier
 --> src/main.rs:6:36
  |
6 | fn x_diff(a: &Point, b: &Point) -> &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 `a` or `b`
help: consider introducing a named lifetime parameter
  |
6 | fn x_diff<'a>(a: &'a Point, b: &'a Point) -> &'a i32 {
  |          ^^^^    ^^^^^^^^^     ^^^^^^^^^     ^^^

Playground link

Meta

Tested versions: 1.47 and 1.49.0-nightly (2020-10-14 e160e5c).

I personally think those misdiagnoses may lead to learners being sent down the wrong path and interacting with the lifetime feature in places where it is not needed, leading to confusion.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-lifetimesArea: Lifetimes / regionsC-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
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions