我尝试打印一棵树(现在是一个链表,但这将被修复):
编译器提示:
或许
use std::io;
use std::rc::Rc;
enum NodeKind {
Branch(Rc<Node>),
Leaf,
}
struct Node {
value: i32,
kind: NodeKind,
}
fn main() {
let leaf = Node { value: 10, kind: NodeKind::Leaf };
let branch = Node { value: 50, kind: NodeKind::Branch(Rc::new(leaf)) };
let root = Node { value: 100, kind: NodeKind::Branch(Rc::new(branch)) };
let mut current = root;
while true {
println!("{}", current.value);
match current.kind {
NodeKind::Branch(next) => {
current = *next;
}
NodeKind::Leaf => {
break;
}
}
}
let mut reader = io::stdin();
let buff = &mut String::new();
let read = reader.read_line(buff);
}
编译器提示:
error[E0507]: cannot move out of borrowed content
--> src/main.rs:24:27
|
24 | current = *next;
| ^^^^^ cannot move out of borrowed content
我只是读取值,不做任何更改。我正在将一个引用的值赋给另一个值,尝试解引用一个 Rc<T>
值并将其存储在本地的 mut
变量中。
也许像这样做可以行:
while true {
println!("{}", current.value);
match ¤t.kind {
&NodeKind::Branch(next) => {
current = next;
}
&NodeKind::Leaf => {
break;
}
}
}
或许
let mut current = &Rc::new(root);
while true {
println!("{}", current.value);
match current.kind {
NodeKind::Branch(next) => {
current = &next;
}
NodeKind::Leaf => {
break;
}
}
}
但我得到了相同的错误,加上'next' does not live long enough
match
子句中借用,但在你的情况下,你受到结构创建方式的限制。即使你借用了,你仍然需要通过Clone
显式地或通过Copy
隐式地克隆它。你似乎正在寻找的是遍历树的迭代器。 - Daniel Fathlet mut current = Rc::new(root)
,这样我想要复制的只有 Rc 和 i32,而不是整个结构体。我只想读取 Rc 地址,解引用它,复制 i32 并打印它,然后读取下一个节点的地址并将当前节点分配给该地址,直到遇到叶子节点为止。这里只涉及到 Rc 和 i32 的复制(这在标准库中已经实现了,包括 Rc)。 - Alex Zhukovskiy