`cannot move out of dereference of `&mut`-pointer` while building a sorted linked list

后端 未结 1 1284
南笙
南笙 2020-12-04 02:56

So, I\'m learning Rust and decided to build a sorted linked list. Everything looks nice until I reach the add method, here\'s the code:

struct NodeItem<\'         


        
相关标签:
1条回答
  • 2020-12-04 03:44

    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 Copyable. 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 Cloneable, 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);
    }
    
    0 讨论(0)
提交回复
热议问题