About Lifetime, Beginner Question

How can I create a struct A which has Vec<B> and Vec<C>, in which each one of C has a reference to B in the vector owned by A? I understand each C's lifetime should be shorter than each element B associated with the C, but I'm confused about Lifetime...

struct B {
}

struct C<'a> {
	b: &'a B
}

struct A<'a> {
	bs: Vec<B>,
	cs: Vec<C>,
}

impl<'a> A<'a> {
	fn add_b(&mut self, b: B) {
		self.bs.push(b);
	}
	fn add_c(&mut self, c: C) {
		self.cs.push(c);
	}
}

Thank you in advance!

I suppose that all you’re missing is adding the parameter 'a to the type C everywhere:

struct B {
}

struct C<'a> {
	b: &'a B
}

struct A<'a> {
	bs: Vec<B>,
	cs: Vec<C<'a>>,
}

impl<'a> A<'a> {
	fn add_b(&mut self, b: B) {
		self.bs.push(b);
	}
	fn add_c(&mut self, c: C<'a>) {
		self.cs.push(c);
	}
}

Edit: My solution above does not really capture the fact that the Cs are supposed to refer to the Bs in the same A. So maybe this is not quite the interface that you want. I guess it depends on your use case in the end. If it doesn’t fit your intended use case then you might want to ask another question where you provide more details about what you’re actually trying to archive.

1 Like

Oh, just that? I thought that was more difficult to express the relationship between B and C.
I guess I'm really misunderstanding. I thought I must put 'a, this guy, right before B somewhere like &'a B because this is all about B and C.
It's difficult. I'll keep on trying to understand this. Thank you!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.