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

a4d7622
Opened by pinkpawkitty at 2017-07-27 18:23:10

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.

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

    Dylan DPC at 2023-03-20 13:07:05

  2. Removing mod interface fixes it, but that's not really a solution.

    Can you try to reproduce this in play.rust-lang.org please? I just removed it from the code you posted and that didn't fix the errors: https://play.rust-lang.org/?gist=19155d33367fd16f9a296a71ec099769&version=stable&backtrace=0

    Hanna Kruppe at 2017-03-02 15:36:02

  3. Correction: by 'removing mod interface', they meant removing the mod wrapping, not the body of the mod. (I helped debug this over IRC).

    eternaleye at 2017-03-02 15:58:04

  4. @rkruppe @eternaleye actually no, I confused things and have removed the section. It's not the case. Sorry to confuse everyone.

    pinkpawkitty at 2017-03-02 16:08:49

  5. I've removed the modules because they seem to have nothing to do with the issue.

    pinkpawkitty at 2017-03-03 10:07:46