cannot borrow variable as mutable because it is also borrowed as immutable while building a self-referential HashMap

前端 未结 1 589
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-26 16:29

I\'m trying to build a self-referential HashMap:

use std::collections::HashMap;

struct Node<\'a> {
    byte: u8,
    map: HashMap

        
1条回答
  •  醉话见心
    2021-01-26 17:33

    Answer

    These types of structures can be hard to make in Rust. The main thing missing from your sample is the use of RefCell which allows for shared references. RefCells move Rust's borrow checking from compile-time to run-time, and thus allows you to pass around the memory location. However, don't start using RefCell everywhere, as it is only suitable for situations like this, and RefCells will cause your program to panic! if you attempt to mutably borrow something while it is already mutably borrowed. This will only work with Nodes created in network; you won't be able to create Nodes that exist purely inside of a single Node.

    Solution

    use std::collections::HashMap;
    use std::cell::RefCell;
    #[derive(Debug)]
    struct Node<'a> {
        byte: u8,
        map: HashMap>>,
    }
    
    fn main() {
        let mut network = HashMap::new();
    
        network.insert(0, RefCell::new(Node { byte: 0, map: HashMap::new() }));
        network.insert(1, RefCell::new(Node { byte: 1, map: HashMap::new() }));
    
        let zero_node = network.get(&0).unwrap();
        zero_node.borrow_mut().byte = 2;
    
        let first_node = network.get(&1).unwrap();
        first_node.borrow_mut().map.insert(-1, zero_node);
    
        println!("{:#?}", network);
    }
    

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