Skip to content

Lifetime inference misses what seems like a simple case #15735

Closed
@zwarich

Description

@zwarich

I distilled this from an example in some actual code I have, although I'm not entirely sure that the distilled example reflects the problem in my original code. The program

struct A;

struct B<'a> {
    a: &'a A,
    b: &'a A,
}

impl <'a> B<'a> {
    fn foo<'b>(&'b self) {
        B {
            a: self.a,
            b: self.b,
        };
    }
}

fn main() { }

fails to compile with this error:

test.rs:10:9: 13:10 error: cannot infer an appropriate lifetime for lifetime parameter `'a due to conflicting requirements
test.rs:10         B {
test.rs:11             a: self.a,
test.rs:12             b: self.b,
test.rs:13         };
test.rs:12:16: 12:22 note: first, the lifetime must be contained by the expression at 12:15...
test.rs:12             b: self.b,
                          ^~~~~~
test.rs:12:16: 12:22 note: ...so that automatically reference is valid at the time of borrow
test.rs:12             b: self.b,
                          ^~~~~~
test.rs:11:16: 11:22 note: but, the lifetime must also be contained by the expression at 11:15...
test.rs:11             a: self.a,
                          ^~~~~~
test.rs:11:16: 11:22 note: ...so that automatically reference is valid at the time of borrow
test.rs:11             a: self.a,
                          ^~~~~~

If I change the program slightly so that foo returns a B<'b> then everything works fine:

struct A;

struct B<'a> {
    a: &'a A,
    b: &'a A,
}

impl <'a> B<'a> {
    fn foo<'b>(&'b self) -> B<'b> {
        B {
            a: self.a,
            b: self.b,
        }
    }
}

fn main() { }

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lifetimesArea: Lifetimes / regionsA-type-systemArea: Type systemE-needs-testCall for participation: An issue has been fixed and does not reproduce, but no test has been added.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions