From 75682bb6c7607b287c5e363834b452e95d139756 Mon Sep 17 00:00:00 2001 From: Hatter Jiang Date: Sun, 22 Mar 2020 18:59:56 +0800 Subject: [PATCH] add list --- single_file_tests/list.rs | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 single_file_tests/list.rs diff --git a/single_file_tests/list.rs b/single_file_tests/list.rs new file mode 100644 index 0000000..bc877ba --- /dev/null +++ b/single_file_tests/list.rs @@ -0,0 +1,39 @@ + +enum List { + Cons(u32, Box), + Nil, +} + +impl List { + fn new() -> List { + List::Nil + } + + fn prepend(self, element: u32) -> List { + List::Cons(element, Box::new(self)) + } + + fn len(&self) -> u32 { + match *self { + List::Nil => 0_u32, + List::Cons(_, ref next) => 1 + next.len(), + } + } + + fn stringify(&self) -> String { + match *self { + List::Nil => format!("Nil"), + List::Cons(this, ref next) => format!("{} -> {}", this, next.stringify()), + } + } +} + +fn main() { + let mut list = List::new(); + list = list.prepend(1); + list = list.prepend(2); + list = list.prepend(3); + + println!("Len: {}", list.len()); + println!("Str: {}", list.stringify()); +} \ No newline at end of file