How can I simultaneously iterate over a Rust HashMap and modify some of its values?

后端 未结 1 1822
一向
一向 2021-01-19 15:58

I\'m trying Advent of Code in Rust this year, as a way of learning the language. I\'ve parsed the input (from day 7) into the following structure:

struct Pro         


        
相关标签:
1条回答
  • 2021-01-19 16:23

    Yes, you can grant internal mutability to the HashMap's values using RefCell:

    struct ProcessTree {
        processes: HashMap<String, RefCell<Process>>,  // change #1
    }
    
    impl ProcessTree {
        fn update_parents(&self) {
            for p in self.processes.values() {
                let p = p.borrow();                    // change #2
                for child_name in &p.children {
                    let mut child = self.processes
                        .get(child_name)               // change #3
                        .expect("Child not found.")
                        .borrow_mut();                 // change #4
                    child.parent = Some(p.name.clone());
                }
            }
        }
    }
    

    borrow_mut will panic at runtime if the child is already borrowed with borrow. This happens if a process is its own parent (which should presumably never happen, but in a more robust program you'd want to give a meaningful error message instead of just panicking).

    I invented some names and made a few small changes (besides the ones specifically indicated) to make this code compile. Notably, p.name.clone() makes a full copy of p.name. This is necessary because both name and parent are owned Strings.

    0 讨论(0)
提交回复
热议问题