diff --git a/linked-list/src/main.rs b/linked-list/src/main.rs index bf48f82..148f8f0 100644 --- a/linked-list/src/main.rs +++ b/linked-list/src/main.rs @@ -5,42 +5,39 @@ enum List { Nil, } -// Methods can be attached to an enum impl List { - // Create an empty list + // Create an empty list. fn new() -> List { - // `Nil` has type `List` List::Nil } - // Consume a list, and return the same list with a new element at its front + // Consume a list, and return the same list with a new element at its front. fn prepend(self: Self, elem: u32) -> List { - // `Cons` also has type List List::Cons(elem, Box::new(self)) } - // Return the length of the list + // Return the length of the list. fn len(self: &Self) -> u32 { // `self` has to be matched, because the behavior of this method - // depends on the variant of `self` + // depends on the variant of `self`. // `self` has type `&List`, and `*self` has type `List`, matching on a - // concrete type `T` is preferred over a match on a reference `&T` + // concrete type `T` is preferred over a match on a reference `&T`. match *self { // Can't take ownership of the tail, because `self` is borrowed; - // instead take a reference to the tail + // instead take a reference to the tail. List::Cons(_, ref tail) => 1 + tail.len(), - // Base Case: An empty list has zero length + // Base Case: An empty list has zero length. List::Nil => 0, } } - // Return representation of the list as a (heap allocated) string + // Return representation of the list as a (heap allocated) string. fn stringify(&self) -> String { match *self { List::Cons(head, ref tail) => { // `format!` is similar to `print!`, but returns a heap - // allocated string instead of printing to the console + // allocated string instead of printing to the console. format!("{}, {}", head, tail.stringify()) } List::Nil => { @@ -51,15 +48,14 @@ impl List { } fn main() { - // Create an empty linked list + // Create an empty linked list. let mut list = List::new(); - // Prepend some elements + // Prepend some elements. list = list.prepend(1); list = list.prepend(2); list = list.prepend(3); - // Show the final state of the list println!("linked list has length: {}", list.len()); println!("{}", list.stringify()); }