user1513132
user1513132

Reputation: 3

How to fix the error `self` does not live long enough when creating a new value that references self?

I am working in Rust, and I am having some trouble getting the ownership system to work for me. I want to give child a reference to its parent when the parent creates the child. Below is the code that I was trying to get working:

struct Child<'a> {
    parent: &'a Parent,
}
impl<'a> Child<'a> {
    fn new(parent: &Parent) -> Child {
        Child { parent: &parent }
    }
}

struct Parent {
    child_count: u32,
}
impl Parent {
    fn new() -> Parent {
        Parent { child_count: 0 }
    }
    fn makeChild(&mut self) -> Child {
        self.child_count += 1;
        Child::new(&self)
    }
}

fn main() {
    let mut parent = Parent::new();
    let child = parent.makeChild();
}

However, I keep getting the following error:

src/main.rs:20:17: 20:21 error: `self` does not live long enough
src/main.rs:20     Child::new(&self)

Upvotes: 0

Views: 710

Answers (1)

Francis Gagn&#233;
Francis Gagn&#233;

Reputation: 65692

self is already a reference, because you declare the function's argument as &mut self, so you don't need to take a reference to it – just use self directly.

impl Parent {
    fn new() -> Parent {
        Parent { child_count: 0 }
    }
    fn makeChild(&mut self) -> Child {
        self.child_count += 1;
        Child::new(self)
    }
}

Upvotes: 2

Related Questions