Skip to content

Instantly share code, notes, and snippets.

@jorendorff
Last active December 2, 2016 00:46
Show Gist options
  • Select an option

  • Save jorendorff/fb36f0e2ba7762ef2806 to your computer and use it in GitHub Desktop.

Select an option

Save jorendorff/fb36f0e2ba7762ef2806 to your computer and use it in GitHub Desktop.
// 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