gpt4 book ai didi

rust - 检索对树值的可变引用

转载 作者:行者123 更新时间:2023-12-03 11:43:51 24 4
gpt4 key购买 nike

披露:这是我的Rust编程课的一项家庭作业问题。我也确实试图理解/学习该 Material 。
因此,我有一棵类似于以下的树(包含更改):

struct Tree<V> {
val: Option<V>,
children: Vec<Tree<V>>
}
我的任务是从根目录搜索树并检索对val的可变引用。这是函数签名:
fn get_mut(&mut self, key: &str) -> Option<&mut V>
该函数本身很简单。我将 self参数设置为 current_node变量并进行搜索,直到找到正确的节点。我已经完成并测试了这部分(我可以看到它使用debug语句在树中搜索)。由于我是通过可变的自己的,所以这是 current_node:
let mut current_node: &mut Tree<V> = self;
为了保持对 current_node的可变引用,在搜索每个树/子树的子级时,我在 iter_mut()上使用 Vec:
for child in current_node.children.iter_mut() {
...
}
找到正确的节点后,我从中取出值并返回:
let val_opt: Option<&mut V> = current_node.val.as_mut();
return match val_opt {
Some(val) => {
return Some(val)
},
None => None
}
但是,我在 child 循环上有一个错误:
cannot borrow `current_node.children` as mutable more than once at a time. mutable borrow starts here in previous iteration of loop.

let's call the lifetime of this reference `'1` (start of the function)

mutable borrow starts here in previous iteration of loop (child loop)

returning this value requires that `current_node.children` is borrowed for `'1` (on the line where I return Some(val) at the very end of the function)
我试图了解为什么会发生这种情况以及如何克服它。从基本搜索来看,它似乎与生命周期有关,但是我对我必须采取的补救措施有些迷失。另外,我无法更改 Tree<V>结构或函数签名。
最少的实现:
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Tree<V> {
val: Option<V>,
children: Vec<(char, Tree<V>)>,
}

fn str_split_first(x: &str) -> Option<(char, &str)> {
let mut chars = x.chars();
let first = chars.next()?;
Some((first, chars.as_str()))
}

impl<V> Tree<V> {
pub fn get_mut(&mut self, key: &str) -> Option<&mut V> {
let mut current_node: &mut Tree<V> = self;
let mut key_index: usize = 0;

loop {
match str_split_first(&key[key_index..]) {
Some((c, _)) => {
let mut found: bool = false;

'child_loop: for (character, child) in current_node.children.iter_mut() {
if c == *character {
current_node = child;
found = true;
break 'child_loop;
}
}

// If nothing was found, this key does not exist.
if found == false {
return None;
}

key_index += 1;
}
_ => break,
}
}

let val_opt: Option<&mut V> = current_node.val.as_mut();
return match val_opt {
Some(val) => return Some(val),
None => None,
};
}
}
Playground link

最佳答案

这里的问题是,您在迭代current_node的子项时正在对其进行修改。 Rust编译器试图保护您免受迭代器无效的影响,但是在这种情况下,这样做确实是正确的,因为在更改current_node的值后,迭代立即停止。
不幸的是,编译器还不够智能,无法看到它。一个简单的解决方法是将新值存储在某个临时变量中,并在循环外部更新current_node。像这样:

let mut found = None;

for (character, child) in current_node.children.iter_mut() {
if c == *character {
found = Some(child);
break;
}
}

current_node = match found {
Some(child) => child,
None => return None,
};
Link to the playground

关于rust - 检索对树值的可变引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66411362/

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