How should I restructure my graph code to avoid an “Cannot borrow variable as mutable more than once at a time” error?

前端 未结 2 1954
小鲜肉
小鲜肉 2020-12-21 15:49

I have a simple graph that successfully compiles:

use std::collections::HashMap;

type Key = usize;
type Weight = usize;

#[derive(Debug)]
pub struct Node<         


        
2条回答
  •  旧时难觅i
    2020-12-21 16:05

    I solved problem by using std::rc::Rc:

    use std::collections::HashMap;
    use std::rc::Rc;
    
    type Key = usize;
    type Weight = usize;
    
    #[derive(Debug)]
    pub struct Node {
        key: Key,
        value: T,
    }
    impl Node {
        fn new(key: Key, value: T) -> Self {
            Node {
                key: key,
                value: value,
            }
        }
    }
    
    #[derive(Debug)]
    pub struct Graph {
        map: HashMap>,
        list: HashMap>>, // <-- Changed
        next_key: Key,
    }
    impl Graph {
        pub fn new() -> Self {
            Graph {
                map: HashMap::new(),
                list: HashMap::new(),
                next_key: 0,
            }
        }
    
        pub fn add_node(&mut self, value: T) -> Rc> {
            // <-- Changed
            let key = self.get_next_key();
            let node = Rc::new(Node::new(key, value)); // <-- Changed
            self.list.insert(key, node.clone()); // <-- Changed
            self.map.insert(key, HashMap::new());
            node
        }
    
        fn get_next_key(&mut self) -> Key {
            let key = self.next_key;
            self.next_key += 1;
            key
        }
    }
    
    fn main() {
        let mut graph = Graph::::new();
        let n1 = graph.add_node(111);
        let n2 = graph.add_node(222);
    }
    

提交回复
热议问题