所以我在第 17 行出现了上述错误,我理解,但没有找到好的解决方法:
struct Node {
node_type: NodeType
}
enum NodeType {
Inner([Box<Node>; 16]),
Leaf(Vec<usize>)
}
impl Node {
fn foo(&mut self) {
match &mut self.node_type {
NodeType::Leaf(_content) => {
// Mutate content
},
NodeType::Inner(children) => {
let index = self.compute_index();
let child = &mut children[index];
child.foo();
}
}
}
fn compute_index(&self) -> usize {
// compute something
0
}
}
我需要
self
是可变的,以在 Leaf
情况下改变其内容。我可以将代码从 compute_index()
复制到我的 foo()
函数中,但这会使 foo()
函数变得不必要的长,并且 compute_index()
内的代码看起来像是一个独立的语义单元。
我也可以将调用移至
compute_index()
语句上方的 match
,但我不需要在所有匹配分支中执行它,因此在这种情况下这会导致不必要的计算,而且看起来也不正确。
我想了很长一段时间,但无法找到一种方法来消除这个错误而不会让我的代码变得糟糕。 有谁知道如何在不使代码变坏的情况下消除错误?
在获取可变借用之前,您可以打乱周围的事物来计算索引吗?
impl Node {
fn foo(&mut self) {
if let NodeType::Leaf(_content) = &mut self.node_type {
// Mutate content
_content.push(42);
} else {
let index = self.compute_index();
if let NodeType::Inner(children) = &mut self.node_type {
let child = &mut children[index];
child.foo();
}
}
}
fn compute_index(&self) -> usize {
// compute something
0
}
}