Skip to content

"cannot infer an appropriate lifetime for automatic coercion" in struct initializer #13405

Closed
@stepancheg

Description

@stepancheg

Code:

struct Foo<'a> {
    i: &'a bool,
    j: Option<&'a int>,
}

impl<'a> Foo<'a> {
    fn bar(&mut self, j: &int) {
        let child = Foo {
            i: self.i,
            j: Some(j)
        };
    }
}

and error is:

/home/vagrant/tmp2.rs:9:16: 9:22 error: cannot infer an appropriate lifetime for automatic coercion due to conflicting requirements
/home/vagrant/tmp2.rs:9             i: self.i,
                                       ^~~~~~
/home/vagrant/tmp2.rs:7:32: 12:6 note: first, the lifetime cannot outlive the lifetime &'a  as defined on the block at 7:31...
/home/vagrant/tmp2.rs:7     fn bar(&mut self, j: &int) {
/home/vagrant/tmp2.rs:8         let child = Foo {
/home/vagrant/tmp2.rs:9             i: self.i,
/home/vagrant/tmp2.rs:10             j: Some(j)
/home/vagrant/tmp2.rs:11         };
/home/vagrant/tmp2.rs:12     }
/home/vagrant/tmp2.rs:9:16: 9:22 note: ...so that reference does not outlive borrowed content
/home/vagrant/tmp2.rs:9             i: self.i,
                                       ^~~~~~
/home/vagrant/tmp2.rs:7:32: 12:6 note: but, the lifetime must be valid for the anonymous lifetime #2 defined on the block at 7:31...
/home/vagrant/tmp2.rs:7     fn bar(&mut self, j: &int) {
/home/vagrant/tmp2.rs:8         let child = Foo {
/home/vagrant/tmp2.rs:9             i: self.i,
/home/vagrant/tmp2.rs:10             j: Some(j)
/home/vagrant/tmp2.rs:11         };
/home/vagrant/tmp2.rs:12     }
/home/vagrant/tmp2.rs:10:16: 10:23 note: ...so that expression is assignable (expected `std::option::Option<&int>` but found `std::option::Option<&int>`)
/home/vagrant/tmp2.rs:10             j: Some(j)
                                        ^~~~~~~
error: aborting due to previous error

Metadata

Metadata

Assignees

No one assigned

    Labels

    E-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