在调用 &'a mut self 方法后,不能一次多次借用可变变量 [英] Cannot borrow variable as mutable more than once at a time after calling a &'a mut self method
问题描述
我的 Graph
对象的生命周期/借用有问题.
I have a problem with lifetimes/borrowing with my Graph
object.
fn main() {
let mut g = Graph {
nodePointer: &mut 0,
edgePointer: &mut 0,
nodes: &mut Vec::new(),
edges: &mut Vec::new(),
};
let node1 = g.add_node((1, 1));
let node2 = g.get_node(0);
}
pub struct Graph<'a> {
pub nodePointer: &'a mut usize,
pub edgePointer: &'a mut usize,
pub nodes: &'a mut Vec<Node>,
pub edges: &'a mut Vec<Edge>,
}
impl<'a> Graph<'a> {
pub fn add_node(&'a mut self, data: (u64, u64)) -> usize {
let id: usize = *self.nodePointer;
self.nodes.push(Node {
id: id,
datum: data,
});
*self.nodePointer += 1;
return id;
}
pub fn get_node(&'a mut self, id: usize) -> &'a Node {
return &self.nodes[id];
}
pub fn add_edge(&'a mut self, source: u64, target: u64, weight: u16) -> usize {
let id: usize = *self.nodePointer;
self.edges.push(Edge {
id: id,
source,
target,
weight,
});
*self.edgePointer = *self.edgePointer + 1;
return id;
}
}
pub struct Node {
pub id: usize,
pub datum: (u64, u64),
}
pub struct Edge {
pub id: usize,
pub source: u64,
pub target: u64,
pub weight: u16,
}
error[E0499]: cannot borrow `g` as mutable more than once at a time
--> src/main.rs:9:17
|
8 | let node1 = g.add_node((1, 1));
| - first mutable borrow occurs here
9 | let node2 = g.get_node(0);
| ^ second mutable borrow occurs here
10 | }
| - first borrow ends here
推荐答案
您的问题源于滥用生命周期,特别是在您的 add_node
签名中:
Your problem arises from a misuse of lifetimes, specifically in your signature of add_node
:
pub fn add_node(&'a mut self, data: (u64, u64)) -> usize
在此签名中,您声明 add_node
在 Graph<'a>
上采用 &'a mut self
;换句话说,你告诉 Rust 这个方法需要在图的生命周期结束之前对图进行可变借用,'a
.但是由于图本身持有对图的引用,因此该引用将被删除的唯一时间是图本身被删除时.
In this signature, you are stating that add_node
takes an &'a mut self
on a Graph<'a>
; in other words, you are telling Rust that this method needs to take a mutable borrow on the graph that can't be dropped before the end of the Graph's lifetime, 'a
. But since it's the graph itself holding a reference to the graph, the only time that reference will be dropped is when the graph itself is dropped.
由于 add_node
不要求您返回对结构中任何对象的引用,因此保持借用是无关紧要的.如果您更改 add_node
方法以删除显式生命周期:
Since add_node
doesn't require you to return a reference to any object within the struct, holding onto that borrow is irrelevant. If you alter your add_node
method to remove the explicit lifetime:
pub fn add_node(&mut self, data: (u64, u64)) -> usize
那么你的例子不再引发错误,因为 add_node
现在只是借用 self
直到它完成函数.(在幕后,这有效地创建了第二个生命周期 'b
并使签名成为 &'b mut self
)
then your example no longer raises an error, because add_node
is now only borrowing self
until it's finished with the function. (Under the hood, this effectively creates a second lifetime 'b
and makes the signature into &'b mut self
)
请参阅游乐场以获取证据.
这篇关于在调用 &'a mut self 方法后,不能一次多次借用可变变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!