Skip to content

Lifetime complaints depend on whether you attach the value to a variable first #48998

Description

@SCdF

(Apologies if this is just me misunderstanding Rust, I'm very new to the language.)

Given:

#[derive(Debug)]
struct Foo<'a> {
    bar: &'a Bar
}
#[derive(Debug)]
struct Bar {
    val: i32
}

fn main() {
    let foo = foo_me();
    println!("{:?}", foo);
}

The following implementation of foo_me works:

fn foo_me<'a>() -> Foo<'a> {
    Foo {
        bar: &Bar {
            val: 42
        }
    }
}

While this one doesn't:

fn foo_me<'a>() -> Foo<'a> {
    let bar = Bar {
        val: 42
    };
    Foo {
        bar: &bar
    }
}

With:

  --> src/main.rs:15:15
   |
15 |         bar: &bar
   |               ^^^ borrowed value does not live long enough
16 |     }
17 | }
   | - borrowed value only lives until here
   |
note: borrowed value must be valid for the lifetime 'a as defined on the function body at 10:1...
  --> src/main.rs:10:1
   |
10 | fn foo_me<'a>() -> Foo<'a> {
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^

I can see what it's complaining about, but I feel like these two examples should function identically. I have a more complicated piece of code that I'm not smart enough to coerce into the working format, so there may be more complicated variants on this which are not solvable.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsC-enhancementCategory: An issue proposing an enhancement or a PR with one.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