Last active
August 14, 2019 06:57
-
-
Save murasesyuka/490e5b5f12c0f27e0d4be1bdd45ffda6 to your computer and use it in GitHub Desktop.
Singly-Linked List Rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** ref | |
| * https://medium.com/@11Takanori/singly-linked-list-in-rust-70a7c2cfa162 | |
| * https://qnighy.hatenablog.com/entry/2017/05/18/070000 | |
| * https://stackoverflow.com/questions/1738758/linked-list-ocaml | |
| */ | |
| #[derive(Debug)] | |
| struct List<T> { | |
| root: Option<Box<Node<T>>>, | |
| } | |
| #[derive(Debug)] | |
| struct Node<T> { | |
| value: T, | |
| next: Option<Box<Node<T>>>, | |
| } | |
| impl<T> List<T> { | |
| fn new() -> List<T> { | |
| List{ root: None } | |
| } | |
| fn push_front(&mut self, value: T) { | |
| self.root = Some(Box::new(Node { | |
| value: value, | |
| next: ::std::mem::replace(&mut self.root, None), | |
| })); | |
| } | |
| fn head(&mut self) -> T { | |
| let root = ::std::mem::replace(&mut self.root, None); | |
| let value = root.unwrap().value; | |
| ::std::mem::replace(&mut self.root, root); | |
| return value; | |
| } | |
| } | |
| fn main() { | |
| let mut l: List<i32> = List::new(); | |
| l.push_front(1); | |
| l.push_front(2); | |
| l.push_front(3); | |
| println!("{:?}", l); | |
| assert_eq!(3, l.head()); | |
| /* | |
| error[E0382]: use of moved value: `root` | |
| --> src\main.rs:28:45 | |
| | | |
| 26 | let root = ::std::mem::replace(&mut self.root, None); | |
| | ---- move occurs because `root` has type `std::option::Option<std::boxed::Box<Node<T>>>`, which does not implement the `Copy` trait | |
| 27 | let value = root.unwrap().value; | |
| | ---- value moved here | |
| 28 | ::std::mem::replace(&mut self.root, root); | |
| | ^^^^ value used here after move | |
| */ | |
| assert_eq!(3, l.head()); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment