Here's a similar example:
enum E { Hello }
struct A(E);
fn main() {
let mut a = A(E::Hello);
let b = &mut a;
let c = b.0;
}
And the errors:
<anon>:7:13: 7:14 error: cannot move out of dereference of `&mut`-pointer
<anon>:7 let c = b.0;
^
<anon>:7:9: 7:10 note: attempting to move value to here
<anon>:7 let c = b.0;
^
<anon>:7:9: 7:10 help: to prevent the move, use `ref c` or `ref mut c` to capture value by reference
<anon>:7 let c = b.0;
^
Note that the compiler tells you how to prevent the error in this case.
The problem is that your self.value
is not Copy
able. That means that when you assign it, you are moving it out of the NodeItem
(self
), thus leaving it no longer fully defined! This would be a bad thing, so Rust prevents you from doing it.
You have to decide what the right way of fixing your problem is. The easiest is to ensure that T
is copyable (or maybe Clone
able, depending on your data). However, you probably don't want to be copying your data all around. I would investigate changing your code to prevent copying the node around and just updating entries. You may need to use something like swap
.
Where I take all the fun out of exploring a new language
#[derive(Debug)]
struct Node<T> {
v: T,
next: Option<Box<Node<T>>>,
}
impl<T> Node<T> {
fn new(v: T) -> Node<T> { Node { v: v, next: None } }
fn push_front(self, head: T) -> Node<T> {
Node {
v: head,
next: Some(Box::new(self)),
}
}
fn push_back(&mut self, tail: T) {
match self.next {
Some(ref mut next) => next.push_back(tail),
None => self.next = Some(Box::new(Node::new(tail))),
}
}
fn push_after(&mut self, v: T) {
let old_next = self.next.take();
let new_next = Node {
v: v,
next: old_next,
};
self.next = Some(Box::new(new_next));
}
}
fn main() {
let mut n = Node::new(2u8);
n.push_back(3u8);
let mut n = n.push_front(0u8);
n.push_after(1u8);
println!("{:?}", n);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…