Skip to content

Lifetime inference falls over with identical lifetimes across trait and implementing struct #40210

Open
@pinkpawkitty

Description

@pinkpawkitty

I tried to write this code:

fn main() {
    let a = XImpl {};
    foo(&a);
}
fn foo(x: &X) {
    x.bar();
}
pub trait X<'a> {
    fn bar(&'a self);
}
pub struct XImpl {}
impl<'a> X<'a> for XImpl {
    fn bar(&'a self) {}
}

I think this should compile, but it fails with: https://gist.github.com/buntpfotenkatze/073cc5d65bdbd0e87b202cfe6013d39c

Replacing fn foo(x: &X) with fn foo<'a>(x: &'a X<'a>) fixes it, but I think the compiler should be able to deduce that the two lifetimes of x are identical.

Edit:
code updated to 2021 ed

current error:

error: lifetime may not live long enough
 --> src/main.rs:6:5
  |
5 | fn foo(x: &dyn X) {
  |        -  - let's call the lifetime of this reference `'1`
  |        |
  |        has type `&dyn X<'2>`
6 |     x.bar();
  |     ^^^^^^^ argument requires that `'1` must outlive `'2`

error: could not compile `playground` (bin "playground") due to previous error

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-inferenceArea: Type inferenceA-lifetimesArea: Lifetimes / regionsC-bugCategory: This is a bug.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions