Skip to content

Commit

Permalink
feat: update linked-list documents
Browse files Browse the repository at this point in the history
  • Loading branch information
1995parham committed Jan 3, 2024
1 parent 7aee9de commit f3f330f
Showing 1 changed file with 11 additions and 15 deletions.
26 changes: 11 additions & 15 deletions linked-list/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 => {
Expand All @@ -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());
}

0 comments on commit f3f330f

Please sign in to comment.