Reference 使用可变引用迭代递归结构并返回最后一个有效引用
我试图递归一个节点结构,修改它们,然后返回我得到的最后一个Reference 使用可变引用迭代递归结构并返回最后一个有效引用,reference,rust,mutable,borrowing,Reference,Rust,Mutable,Borrowing,我试图递归一个节点结构,修改它们,然后返回我得到的最后一个节点。我使用一个函数解决了循环中可变引用的问题。如果我尝试将可变引用返回到最后一个节点,我会得到一个使用移动值的错误: #[derive(Debug)] struct Node { children: Vec<Node>, } impl Node { fn new(children: Vec<Self>) -> Self { Self { children } }
节点。我使用一个函数解决了循环中可变引用的问题。如果我尝试将可变引用返回到最后一个节点
,我会得到一个使用移动值的错误:
#[derive(Debug)]
struct Node {
children: Vec<Node>,
}
impl Node {
fn new(children: Vec<Self>) -> Self {
Self { children }
}
fn get_last(&mut self) -> Option<&mut Node> {
self.children.last_mut()
}
}
fn main() {
let mut root = Node::new(vec![Node::new(vec![])]);
let current = &mut root;
println!("Final: {:?}", get_last(current));
}
fn get_last(mut current: &mut Node) -> &mut Node {
loop {
let temp = current;
println!("{:?}", temp);
match temp.get_last() {
Some(child) => { current = child },
None => break,
}
}
current
}
如果我返回临时值而不是中断,我会得到一个错误不能多次借用为可变的
fn get_last(mut current: &mut Node) -> &mut Node {
loop {
let temp = current;
println!("{:?}", temp);
match temp.get_last() {
Some(child) => { current = child },
None => return temp,
}
}
}
error[E0499]:不能一次多次将“*temp”作为可变项借用
-->测试。rs:47:28
|
43 |匹配温度获取最后一次(){
|----第一个可变借用发生在这里
...
47 |无=>返回温度,
|^^^^第二个可变借用发生在此处
48 | }
49 | }
|-第一次借钱到此为止
如何使用可变引用遍历结构并返回最后一个节点
?我已经搜索过了,但还没有找到解决这个问题的方法
我无法使用,因为它会给我多次错误:
fn get_last(mut current: &mut Node) -> &mut Node {
loop {
let temp = current;
println!("{:?}", temp);
match temp.get_last() {
Some(child) => current = child,
None => current = temp,
}
}
current
}
这确实不同于我们。如果我们看一下答案,稍微修改一下,我们可以看到它匹配一个值,并且能够返回在终端案例中匹配的值。也就是说,返回值是一个选项
:
fn back(&mut self) -> &mut Option<Box<Node>> {
let mut anchor = &mut self.root;
loop {
match {anchor} {
&mut Some(ref mut node) => anchor = &mut node.next,
other => return other, // transferred ownership to here
}
}
}
请注意,我们正在使用和中公开的所有技术
使用进行中的,我们可以稍微简化get\u last\u或\u self
以避免布尔值:
fn get_last_or_self(&mut self) -> LastOrNot<'_> {
match self.children.last_mut() {
Some(l) => LastOrNot::Last(l),
None => LastOrNot::NotLast(self),
}
}
另见:
最后一个最简洁的版本是get_last
,它现在可以与-Z polonius
(每晚1.44)一起使用。
enum LastOrNot<'a> {
Last(&'a mut Node),
NotLast(&'a mut Node),
}
impl Node {
fn get_last_or_self(&mut self) -> LastOrNot<'_> {
match self.children.is_empty() {
false => LastOrNot::Last(self.children.last_mut().unwrap()),
true => LastOrNot::NotLast(self),
}
}
fn get_last(mut current: &mut Node) -> &mut Node {
loop {
match { current }.get_last_or_self() {
LastOrNot::Last(child) => current = child,
LastOrNot::NotLast(end) => return end,
}
}
}
}
fn get_last_or_self(&mut self) -> LastOrNot<'_> {
match self.children.last_mut() {
Some(l) => LastOrNot::Last(l),
None => LastOrNot::NotLast(self),
}
}
fn get_last(mut current: &mut Node) -> &mut Node {
while let Some(child) = current.get_last() {
current = child;
}
current
}