使用可变引用迭代递归结构并返回最后一个有效引用
Iterating through a recursive structure using mutable references and returning the last valid reference
我正在尝试向下递归节点结构,修改它们,然后 returning 我到达的最后一个 Node
。我使用 example in the non-lexical lifetimes RFC 解决了循环中可变引用的问题。如果我尝试 return 对最后一个 Node
的可变引用,我会收到 use of moved value
错误:
#[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
}
给出这个错误
error[E0382]: use of moved value: `*current`
--> test.rs:51:5
|
40 | let temp = current;
| ---- value moved here
...
51 | current
| ^^^^^^^ value used here after move
|
= note: move occurs because `current` has type `&mut Node`, which does not implement the `Copy` trait
如果我 return 临时值而不是破坏,我得到错误 cannot borrow as mutable more than once
。
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]: cannot borrow `*temp` as mutable more than once at a time
--> test.rs:47:28
|
43 | match temp.get_last() {
| ---- first mutable borrow occurs here
...
47 | None => return temp,
| ^^^^ second mutable borrow occurs here
48 | }
49 | }
| - first borrow ends here
如何使用可变引用和 return 最后一个 Node
遍历结构?我已经搜索过了,但我还没有找到针对这个特定问题的任何解决方案。
我不能使用 因为它给我一个借用不止一次的错误:
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
}
这确实与不同。如果我们查看那里的答案,稍微修改一下,我们可以看到它匹配一个值并且能够 return 在终端案例中匹配的值。也就是说,return 值是 Option
:
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
}
}
}
你的案子在两个方面很复杂:
- 缺少non-lexical lifetimes.
您想要在一种情况下(有 children)而不是在另一种情况下(没有 children)获取可变引用和 "give it up" ).这在概念上与此相同:
fn maybe_identity<T>(_: T) -> Option<T> { None }
fn main() {
let name = String::from("vivian");
match maybe_identity(name) {
Some(x) => println!("{}", x),
None => println!("{}", name),
}
}
编译器无法判断 None
案例可以(非常 理论上)继续使用 name
.
straight-forward 解决方案是明确编码此 "get it back" 操作。我们创建一个 return 在没有 children 的情况下 &mut self
的枚举,一个 return 那个枚举的辅助方法,并重写主要方法以使用辅助方法:
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,
}
}
}
}
请注意,我们使用了 和 中公开的所有技术。
使用 in-progress reimplementation of NLL,我们可以稍微简化 get_last_or_self
以避免布尔值:
fn get_last_or_self(&mut self) -> LastOrNot<'_> {
match self.children.last_mut() {
Some(l) => LastOrNot::Last(l),
None => LastOrNot::NotLast(self),
}
}
Polonius 的最终版本应该允许将整个问题简化为非常 的简单形式:
fn get_last(mut current: &mut Node) -> &mut Node {
while let Some(child) = current.get_last() {
current = child;
}
current
}
另请参阅:
我正在尝试向下递归节点结构,修改它们,然后 returning 我到达的最后一个 Node
。我使用 example in the non-lexical lifetimes RFC 解决了循环中可变引用的问题。如果我尝试 return 对最后一个 Node
的可变引用,我会收到 use of moved value
错误:
#[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
}
给出这个错误
error[E0382]: use of moved value: `*current`
--> test.rs:51:5
|
40 | let temp = current;
| ---- value moved here
...
51 | current
| ^^^^^^^ value used here after move
|
= note: move occurs because `current` has type `&mut Node`, which does not implement the `Copy` trait
如果我 return 临时值而不是破坏,我得到错误 cannot borrow as mutable more than once
。
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]: cannot borrow `*temp` as mutable more than once at a time
--> test.rs:47:28
|
43 | match temp.get_last() {
| ---- first mutable borrow occurs here
...
47 | None => return temp,
| ^^^^ second mutable borrow occurs here
48 | }
49 | }
| - first borrow ends here
如何使用可变引用和 return 最后一个 Node
遍历结构?我已经搜索过了,但我还没有找到针对这个特定问题的任何解决方案。
我不能使用
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
}
这确实与Option
:
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
}
}
}
你的案子在两个方面很复杂:
- 缺少non-lexical lifetimes.
您想要在一种情况下(有 children)而不是在另一种情况下(没有 children)获取可变引用和 "give it up" ).这在概念上与此相同:
fn maybe_identity<T>(_: T) -> Option<T> { None } fn main() { let name = String::from("vivian"); match maybe_identity(name) { Some(x) => println!("{}", x), None => println!("{}", name), } }
编译器无法判断
None
案例可以(非常 理论上)继续使用name
.
straight-forward 解决方案是明确编码此 "get it back" 操作。我们创建一个 return 在没有 children 的情况下 &mut self
的枚举,一个 return 那个枚举的辅助方法,并重写主要方法以使用辅助方法:
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,
}
}
}
}
请注意,我们使用了
使用 in-progress reimplementation of NLL,我们可以稍微简化 get_last_or_self
以避免布尔值:
fn get_last_or_self(&mut self) -> LastOrNot<'_> {
match self.children.last_mut() {
Some(l) => LastOrNot::Last(l),
None => LastOrNot::NotLast(self),
}
}
Polonius 的最终版本应该允许将整个问题简化为非常 的简单形式:
fn get_last(mut current: &mut Node) -> &mut Node {
while let Some(child) = current.get_last() {
current = child;
}
current
}
另请参阅: