Last active
December 2, 2016 00:46
-
-
Save jorendorff/fb36f0e2ba7762ef2806 to your computer and use it in GitHub Desktop.
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
| // push() method for a singly-linked list in Rust?! | |
| use std::rc::Rc; | |
| #[derive(Debug, PartialEq)] | |
| enum List<T> { | |
| Nil, | |
| Cons(Rc<(T, List<T>)>) | |
| } | |
| impl<T> List<T> { | |
| fn push_front(&mut self, value: T) { | |
| let mut tmp = List::Nil; | |
| std::mem::swap(&mut tmp, self); | |
| *self = List::Cons(Rc::new((value, tmp))); | |
| } | |
| } | |
| #[test] | |
| fn push_tests() { | |
| let mut my_list = List::Nil; | |
| my_list.push_front("world"); | |
| my_list.push_front("hello"); | |
| assert_eq!(my_list, | |
| List::Cons(Rc::new(("hello", | |
| List::Cons(Rc::new(("world", List::Nil))))))); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment