0

I want to have a list of items in a struct to reference other items from another list in the same struct. I can do this with Rc&RefCell but then code turns into a mess and I feel that employing Rcs for such a basic thing is an overkill. So it looks like

struct A <'a> {
    items_b:Vec<B>,
    items_c:Vec<C<'a>>
}
...

struct C<'c> {
    item_b: &'c B
}

and the method to add an item

    fn add_c(&mut self, item_b_index:usize) {
        self.items_c.push(C::new(self.items_b.get(item_b_index).unwrap()))
    }

but it either fails with

cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements

or, if I add lifetime to mut self, with

cannot borrow a as mutable more than once at a time

so it becomes unusable. And I don't understand why lifetime matters here at all...

Full example in playground.

Any help is highly appreciated!

user656449
  • 2,950
  • 2
  • 30
  • 43
  • 2
    What you are describing is a self-referential struct (with some disguise). There are many threads here about this, so this one here will probably get closed as duplicate by you-know-whom. – user2722968 May 30 '21 at 14:54
  • hmm, I thought it looks more lie a tree rather than a cycle to be self-referential struct... – user656449 May 30 '21 at 15:58
  • 1
    `self.items_c` contains reference to `self.items_b`, by construction, so `self` as a whole is indeed self-referential. – Cerberus May 30 '21 at 16:04

0 Answers0