0

我正在尝试建立一个自我参照HashMap

use std::collections::HashMap;

struct Node<'a> {
    byte: u8,
    map: HashMap<i32, &'a Node<'a>>,
}

fn main() {
    let mut network = HashMap::<u32, Node>::new();

    network.insert(0, Node { byte: 0, map: HashMap::<i32, &Node>::new() });
    network.insert(1, Node { byte: 1, map: HashMap::<i32, &Node>::new() });

    let zeroeth_node = network.get(&0).unwrap();
    let mut first_node = network.get_mut(&1).unwrap();

    first_node.map.insert(-1, zeroeth_node);
}

我遇到了借用检查器错误,但我不明白它的来源——是我更新HashMap错误的方法,还是我对它的自我引用使用?

错误:

<anon>:15:26: 15:33 error: cannot borrow `network` as mutable because it is also borrowed as immutable [E0502]
<anon>:15     let mut first_node = network.get_mut(&1).unwrap();
                                   ^~~~~~~
<anon>:14:24: 14:31 note: previous borrow of `network` occurs here; the immutable borrow prevents subsequent moves or mutable borrows of `network` until the borrow ends
<anon>:14     let zeroeth_node = network.get(&0).unwrap();
                                 ^~~~~~~
<anon>:18:2: 18:2 note: previous borrow ends here
<anon>:8 fn main() {
...
<anon>:18 }
          ^
4

1 回答 1

2

回答

这些类型的结构在 Rust 中很难构建。您的示例中缺少的主要内容是RefCell允许共享引用的使用。RefCells 将 Rust 的借用检查从编译时转移到运行时,因此允许您传递内存位置。但是,不要RefCell在任何地方开始使用,因为它只适用于这样的情况,如果你试图在已经可变借用的东西时可变地借用, RefCells 将导致你的程序。panic!这仅适用于在;Node中创建的 s network您将无法创建Node纯粹存在于单个Node.

解决方案

use std::collections::HashMap;
use std::cell::RefCell;
#[derive(Debug)]
struct Node<'a> {
    byte: u8,
    map: HashMap<i32, &'a RefCell<Node<'a>>>,
}

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);
}
于 2016-02-21T14:23:57.787 回答