Skip to content

Lifetime inference inconsistency with borrowed pointer fields #8845

Closed
@sfackler

Description

@sfackler
use std::cell::Cell;

struct Foo<'self> {
    f: Cell<&'self fn()>
}

struct Bar<'self> {
    f: &'self Foo<'self>
}

impl<'self> Foo<'self> {
    fn foo<'a>(&'a self) -> Bar<'a> {
        Bar { f: self }
    }
}

fails to compile with

test.rs:13:8: 13:11 error: cannot infer an appropriate lifetime due to conflicting requirements
test.rs:13         Bar { f: self }
                   ^~~
test.rs:12:36: 14:5 note: first, the lifetime cannot outlive the lifetime &'a  as defined on the block at 12:36...
test.rs:12     fn foo<'a>(&'a self) -> Bar<'a> {
test.rs:13         Bar { f: self }
test.rs:14     }
test.rs:13:8: 13:11 note: ...due to the following expression
test.rs:13         Bar { f: self }
                   ^~~
test.rs:12:36: 14:5 note: but, the lifetime must be valid for the lifetime &'self  as defined on the block at 12:36...
test.rs:12     fn foo<'a>(&'a self) -> Bar<'a> {
test.rs:13         Bar { f: self }
test.rs:14     }
test.rs:13:17: 13:23 note: ...due to the following expression
test.rs:13         Bar { f: self }
                            ^~~~~~
error: aborting due to previous error

but removing the Cell compiles correctly:

struct Foo<'self> {
    f: &'self fn()
}

struct Bar<'self> {
    f: &'self Foo<'self>
}

impl<'self> Foo<'self> {
    fn foo<'a>(&'a self) -> Bar<'a> {
        Bar { f: self }
    }
}

It turns out that using 'self instead of 'a fixes the problem:

use std::cell::Cell;

struct Foo<'self> {
    f: Cell<&'self fn()>
}

struct Bar<'self> {
    f: &'self Foo<'self>
}

impl<'self> Foo<'self> {
    fn foo(&'self self) -> Bar<'self> {
        Bar { f: self }
    }
}

I would think that all three examples should compile, since the lifetime bounds of 'a and 'self should intersect properly.

cc @nikomatsakis

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions