The same item in 2 vectors


#1

Hello. Could any one help me with one problem.

Person

use std::string::String;

pub struct Person {
  pub name: String,
  pub adult: bool,
  pub children: Vec<Person>,
}

impl Default for Person {
  fn default() -> Person {
    Person {
      name: String::default(),
      adult: bool::default(),
      children: vec![],
    }
  }
}

Example tree

let mut tree: Vec<Person> = vec![
   Person {
     name: "Grand parent".to_string(),
     adult: true,
     children: vec![
         Person {
           name: "Someone else's parent".to_string(),
           adult: false,
           children: vec![]
        },
         Person {
           name: "Parent".to_string(),
           adult: true,
           children: vec![
               Person {
                 name: "I want access this".to_string(),
                 adult: true,
                 children: vec![]
              }
           ]
        }
     ]
   }
];

What I want is when I change any data of person in adults_list, it will automatically update inside tree.

Example

let mut adults_list: Vec<Person> = vec![tree[0].children[1].children[0]]; // THIS PART THAT I DON'T KNOW

adults_list[0].name = "SUCCESS";

// In tree it would look like this

let mut tree: Vec<Person> = vec![
   Person {
     name: "Grand parent",
     adult: true,
     children: vec![
         Person {
           name: "Someone else's parent",
           adult: false,
           children: vec![]
        },
         Person {
           name: "Parent",
           adult: true,
           children: vec![
               Person {
                 name: "SUCCESS",
                 adult: true,
                 children: vec![]
              }
           ]
        }
     ]
   }
];

#2

You’ll need to employ interior mutability with Rc<RefCell<...>> and then share clones of the Person values. One example would be playground.


#3

@vitalyd Thank you so much for help!


#4

If you can change the type of adults_list to Vec<&mut Person>, and have it living less than tree, you can have some much simpler code: Playground


#5

Good point @carlomilanesi. For some reason, I immediately assumed the desire is to store them in different vecs with different lifetimes.

Also, mutable borrows like this will be simple for borrowing a single Person, but you’ll need split_at_mut() gymnastics to borrow several.