From f40981544c161b750e9890a1471e87b0582241a8 Mon Sep 17 00:00:00 2001 From: Dan Buch Date: Sat, 11 Sep 2021 21:03:58 -0400 Subject: [PATCH] RBE custom types enum testcase linked list --- .../custom_types_enum_testcase_linked_list.rs | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 rustbyexample/custom_types/custom_types_enum_testcase_linked_list.rs diff --git a/rustbyexample/custom_types/custom_types_enum_testcase_linked_list.rs b/rustbyexample/custom_types/custom_types_enum_testcase_linked_list.rs new file mode 100644 index 0000000..a6c8fcf --- /dev/null +++ b/rustbyexample/custom_types/custom_types_enum_testcase_linked_list.rs @@ -0,0 +1,45 @@ +use crate::List::*; + +enum List { + Cons(u32, Box), + Nil, +} + +impl List { + fn new() -> List { + Nil + } + + fn prepend(self, elem: u32) -> List { + Cons(elem, Box::new(self)) + } + + fn len(&self) -> u32 { + match *self { + Cons(_, ref tail) => 1 + tail.len(), + Nil => 0, + } + } + + fn stringify(&self) -> String { + match *self { + Cons(head, ref tail) => { + format!("{}, {}", head, tail.stringify()) + } + Nil => { + format!("Nil") + } + } + } +} + +fn main() { + let mut list = List::new(); + + list = list.prepend(1); + list = list.prepend(2); + list = list.prepend(3); + + println!("linked list has length: {}", list.len()); + println!("{}", list.stringify()); +}