我试图递归一个节点结构,修改它们,然后返回Node我得到的最后一个。我使用非词法生命周期 RFC 中的示例解决了循环中可变引用的问题。如果我尝试将可变引用返回到 last 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; …Run Code Online (Sandbox Code Playgroud)