我想创建一个简单的链表并向其中添加一个值。为了使这段代码在第42行第二个root.print()
调用时输出100 50 10 5
,应如何实现add
方法?
use std::rc::Rc;
struct Node {
value: i32,
next: Option<Box<Node>>,
}
impl Node {
fn print(&self) {
let mut current = self;
loop {
println!("{}", current.value);
match current.next {
Some(ref next) => {
current = &**next;
}
None => break,
}
}
}
fn add(&mut self, node: Node) {
let item = Some(Box::new(node));
let mut current = self;
loop {
match current.next {
None => current.next = item,
_ => {}
//Some(next) => { current = next; }
}
}
}
}
fn main() {
let leaf = Node {
value: 10,
next: None,
};
let branch = Node {
value: 50,
next: Some(Box::new(leaf)),
};
let mut root = Node {
value: 100,
next: Some(Box::new(branch)),
};
root.print();
let new_leaf = Node {
value: 5,
next: None,
};
root.add(new_leaf);
root.print();
}
我已经按照以下方式重新编写了这个函数:
fn add(&mut self, node: Node) {
let item = Some(Box::new(node));
let mut current = self;
loop {
match current {
&mut Node {
value: _,
next: None,
} => current.next = item,
_ => {}
//Some(next) => { current = next; }
}
}
}
但编译器报错:
error[E0382]: use of moved value: `item`
--> <anon>:28:40
|
28 | None => current.next = item,
| ^^^^ value moved here in previous iteration of loop
|
= note: move occurs because `item` has type `std::option::Option<std::boxed::Box<Node>>`, which does not implement the `Copy` trait
我不明白为什么它说该项曾被移动,如果它只使用了一次,以及如何实现Some(_)
分支以迭代列表?
kind
应该是一个引用(&mut T
)而不是一个普通的值(T
)? - Matthieu M.newLeaf
之后,带有value
的叶子节点应该变成一个分支节点。 - Alex Zhukovskiystd::collections::LinkedList
),它说你可以push_back
一个元素,但你也可以将一个列表append
到另一个列表中。 - bluss