gpt4 book ai didi

rust - 在调用 &'a mut self 方法后,不能一次多次借用可变变量

转载 作者:行者123 更新时间:2023-11-29 08:27:01 30 4
gpt4 key购买 nike

我的 Graph 对象存在生命周期/借用问题。

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 的签名中:

pub fn add_node(&'a mut self, data: (u64, u64)) -> usize

在此签名中,您声明 add_node需要 &'a mut selfGraph<'a> 上;换句话说,你是在告诉 Rust 这个方法需要在图的生命周期结束前不能被删除的可变借用,'a .但由于它是图本身持有对图的引用,因此唯一会删除该引用的时间是图本身被删除时。

add_node不需要您返回对结构中任何对象的引用,保留该借用是无关紧要的。如果你改变你的 add_node删除显式生命周期的方法:

pub fn add_node(&mut self, data: (u64, u64)) -> usize

然后您的示例不再引发错误,因为 add_node现在只借self直到它完成函数。 (在引擎盖下,这有效地创建了第二个生命周期 'b 并将签名变为 &'b mut self )

参见 the playground为证。

关于rust - 在调用 &'a mut self 方法后,不能一次多次借用可变变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49928848/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com