【发布时间】:2020-11-04 23:42:56
【问题描述】:
我在 Rust 中有一个 Graph 数据结构:
type NodeIndex = usize;
struct Graph {
nodes: Vec<NodeIndex>,
edges: Vec<(NodeIndex, NodeIndex)>,
}
我想遍历函数内的所有节点并调用一个函数,该函数使用每个节点作为元素来改变图形,比如:
impl Graph {
fn mutate_fn(&mut self) {
for node in self.nodes {
self.mutate_using_node(node);
}
}
fn mutate_using_node(&mut self, node: NodeIndex) {
// mutate self here
}
}
这不起作用,因为我会有多个可变引用。我也不能通过 &self,从那时起我就会有一个可变和不可变的引用。这在 Rust 中是如何处理的?
【问题讨论】:
-
self的哪些部分会读取mutate_using_node,它会发生什么变异? -
@SolomonUcko 它只读取和变异边缘变量。将 'mutate_using_node' 重写为静态方法是否有意义,该方法接受对边和我们当前迭代的节点的可变引用?
-
我推荐阅读Niko's blog post on interprocedural conflicts——它涵盖了此类问题的几种通用解决方案。
-
@eager2learn 在为方法实现partial borrowing 之前,这可能是最简单和最有效的解决方案。你也可以试试the
partial_refcrate,不过我不太了解。
标签: rust borrow-checker