Singly-Linked List in Rust

限于喜欢 提交于 2019-12-02 04:25:44
ljedrz

Your issue is that you are attempting to use a value (node) after having moved it; since Box<Node<T>> does not implement Copy, when you use it in the match expression:

match self.tail {
    None => self.head = Some(node),
    Some(ref mut tail) => tail.append(node),
}

node is moved either to self.head or to self.tail and can no longer be used later. Other than reading the obligatory Learning Rust With Entirely Too Many Linked Lists to see the different ways in which you can implement linked lists in Rust, I suggest that you first do some more research in the field of Rust's basic concepts, especially:

You can go with something simpler than that, only using your nodes

use std::fmt;

struct Payload {
  id: i32,
  value: i32,
}

impl fmt::Display for Payload {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "({}, {})", self.id, self.value)
    }
}

struct Node<T> {
    element: T,
    next: Option<Box<Node<T>>>,
}

impl<T> Node<T> where T: std::fmt::Display{
    fn new(element: T) -> Self {
        Node {
            element: element,
            next: None,
        }
    }

    fn append(&mut self, element: T) {
        match &mut self.next {
            None => {let n = Node {
                        element: element,
                        next: None,
                    };
                    self.next = Some(Box::new(n));
            },
            Some(ref mut x) => x.append(element),
        }
    }

    fn list(& self) {
        println!("{}", self.element);
        match &self.next {
            None => {},
            Some(x) => x.list(),
        }
    }
}

fn main(){
  let mut h = Node::new(Payload {id:1, value:1});
  h.append(Payload {id:2, value:2});
  h.append(Payload {id:3, value:3});
  h.append(Payload {id:4, value:4});
  h.append(Payload {id:5, value:5});
  h.list();
  h.append(Payload {id:6, value:6});
  h.list();
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!