Skip to content

Very unhelpful error message cannot infer an appropriate lifetime for autoref #22537

Closed
@mvdnes

Description

@mvdnes

When compiling the following code:

use std::cell::{RefCell, RefMut};

trait FooTrait {
    fn footrait(&mut self);
}

struct Foo;
impl FooTrait for Foo {
    fn footrait(&mut self) { () }
}

impl<'a> FooTrait for RefMut<'a, Foo> {
    fn footrait(&mut self) { () }
}

struct Bar {
    bar: RefCell<Foo>,
}
impl Bar {
    fn foobox(&self) -> Box<FooTrait> {
        let inner = self.bar.borrow_mut();
        Box::new(inner)
    }
}

I get the following (confusing) error message:

<anon>:21:30: 21:42 error: cannot infer an appropriate lifetime for autoref due to conflicting requirements
<anon>:21         let inner = self.bar.borrow_mut();
                                       ^~~~~~~~~~~~
<anon>:21:21: 21:29 note: first, the lifetime cannot outlive the expression at 21:20...
<anon>:21         let inner = self.bar.borrow_mut();
                              ^~~~~~~~
<anon>:21:21: 21:29 note: ...so that auto-reference is valid at the time of borrow
<anon>:21         let inner = self.bar.borrow_mut();
                              ^~~~~~~~
<anon>:21:21: 21:42 note: but, the lifetime must be valid for the method call at 21:20...
<anon>:21         let inner = self.bar.borrow_mut();
                              ^~~~~~~~~~~~~~~~~~~~~
<anon>:21:21: 21:29 note: ...so that method receiver is valid for the method call
<anon>:21         let inner = self.bar.borrow_mut();
                              ^~~~~~~~

After a lot of trial-and-error I noticed I had to do the following change:

// old:
     fn foobox(&self) -> Box<FooTrait> {
// new:
     fn foobox<'a>(&'a self) -> Box<FooTrait + 'a> {

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-trait-systemArea: Trait system

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions