0

I am trying to implement a recursive struct:

struct Frame<'a> {
    parent: Option<&'a Frame<'a>>,
}

impl<'a> Frame<'a> {
    fn create_child_frame<'b>(&self) -> Frame<'b>
    where
        'a: 'b,
    {
        Frame { parent: Some(self) }
    }
}

This doesn't compile, since according to the compiler there are conflicting lifetime arguments here:

error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
  --> src/lib.rs:10:25
   |
10 |         Frame { parent: Some(self) }
   |                         ^^^^^^^^^^
   |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 6:5...
  --> src/lib.rs:6:5
   |
6  | /     fn create_child_frame<'b>(&self) -> Frame<'b>
7  | |     where
8  | |         'a: 'b,
9  | |     {
10 | |         Frame { parent: Some(self) }
11 | |     }
   | |_____^
note: ...so that reference does not outlive borrowed content
  --> src/lib.rs:10:30
   |
10 |         Frame { parent: Some(self) }
   |                              ^^^^
note: but, the lifetime must be valid for the lifetime `'b` as defined on the method body at 6:27...
  --> src/lib.rs:6:27
   |
6  |     fn create_child_frame<'b>(&self) -> Frame<'b>
   |                           ^^
note: ...so that the expression is assignable
  --> src/lib.rs:10:9
   |
10 |         Frame { parent: Some(self) }
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   = note: expected  `Frame<'b>`
              found  `Frame<'_>`

Implementing the method as a function (which as far as I can tell does exactly the same) does compile:

fn create_child_frame<'b, 'a: 'b>(parent: &'a Frame<'a>) -> Frame<'b> {
    Frame {
        parent: Some(parent),
    }
}

What am I doing wrong?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
chuck
  • 1,420
  • 4
  • 19
  • 1
    It looks like your question might be answered by the answers of [What is the difference between '&self' and '&'a self'?](https://stackoverflow.com/q/45833618/155423). If not, please **[edit]** your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Jul 08 '20 at 20:05
  • 1
    It does. Strange I couldn't find it. Thanks! – chuck Jul 08 '20 at 20:12

0 Answers0