#Pushing to a vector with a lifetime

19 messages · Page 1 of 1 (latest)

heady bloom
#

I have the following code:

    value: &'a str,
    children: Option<Vec<Parent<'a>>>,
}

impl<'a> Parent<'a> {
    pub fn new(value: &'a str, children: Option<Vec<Parent<'a>>>) -> Self {
        Self { value, children }
    }

    pub fn add_child(&'a mut self, parent: Parent<'a>) {
        self.children.as_mut().unwrap().push(parent);
    }
}

And I can't figure out how to call add_child() twice without getting the error parent was mutably borrowed here in the previous iteration of the loop. When I use &'static it works, but I would like to know the proper way to fix this

frozen nimbus
#

also Option<Vec> is a weird and inconvenient type

#

an empty Vec is good enough (it doesn't allocate)

heady bloom
#

i see, thank you for the help! I think i sort of get why removing the 'a works, but i can't quite put it into words haha

heady bloom
heady bloom
frozen nimbus
#

although that's almost folklore, it's not really explained anywhere

heady bloom
#

can you correct me if my explanation is wrong? let's say i have this code:

fn main() {
    let mut parent = Parent::new("", Some(vec![]));
    parent.add_child(Parent::new("", None));
    parent.add_child(Parent::new("", None));
}

is the lifetime of parent the same as that of main? if it is, then when add_child() is called for the first time, it holds onto a mutable reference of parent for the lifetime of main, which is why the second add_child() cannot have another mutable reference to parent

frozen nimbus
#

yep, that's more or less it

#

although there's no explanation why it has to hold it for the whole main

#

that involves variance, which is a complicated topic

#

one more thing is that it's possible that a &'a self could work fine

#

that also has to do with variance

heady bloom
#

i see, is it something that would change my view on this drastically?

frozen nimbus
#

I'm not sure 😅

heady bloom
#

haha, maybe i should go and read up on it

#

but thanks so much for this, i managed to learn a lot