【发布时间】:2016-04-12 07:02:11
【问题描述】:
我有一个成功编译的简单图表:
use std::collections::HashMap;
type Key = usize;
type Weight = usize;
#[derive(Debug)]
pub struct Node<T> {
key: Key,
value: T,
}
impl<T> Node<T> {
fn new(key: Key, value: T) -> Self {
Node {
key: key,
value: value,
}
}
}
#[derive(Debug)]
pub struct Graph<T> {
map: HashMap<Key, HashMap<Key, Weight>>,
list: HashMap<Key, Node<T>>,
next_key: Key,
}
impl<T> Graph<T> {
pub fn new() -> Self {
Graph {
map: HashMap::new(),
list: HashMap::new(),
next_key: 0,
}
}
pub fn add_node(&mut self, value: T) -> &Node<T> {
let node = self.create_node(value);
node
}
fn create_node(&mut self, value: T) -> &Node<T> {
let key = self.get_next_key();
let node = Node::new(key, value);
self.list.insert(key, node);
self.map.insert(key, HashMap::new());
self.list.get(&key).unwrap()
}
fn get_next_key(&mut self) -> Key {
let key = self.next_key;
self.next_key += 1;
key
}
}
但是使用时编译失败:
fn main() {
let mut graph = Graph::<i32>::new();
let n1 = graph.add_node(111);
let n2 = graph.add_node(222);
}
错误:
error[E0499]: cannot borrow `graph` as mutable more than once at a time
--> src/main.rs:57:14
|
56 | let n1 = graph.add_node(111);
| ----- first mutable borrow occurs here
57 | let n2 = graph.add_node(222);
| ^^^^^ second mutable borrow occurs here
58 | }
| - first borrow ends here
我见过所有类似的问题。我知道这是失败的,因为方法Graph::add_node() 使用&mut self。在所有类似的问题中,一般的答案是“重组你的代码”。我不明白我该怎么办?我应该如何重构这段代码?
【问题讨论】:
-
您的代码示例过于简单,我们无法为您提供好的建议。您可以简单地将
let n1 = graph.add_node(111);放入一个块中,然后您的代码就可以工作了,但我很确定这不是您想要的。 -
@ker 这不是例子。是培训项目。我想创建一个简单的图表。但是我不能给它添加一些节点。
-
您不能简单地返回
Key而不是&Node吗?除了创建边缘的关键之外,您不需要任何东西