Testcase: linked-list

A common use for enums is to create a linked-list:

  1. use List::*;
  2. enum List {
  3. // Cons: Tuple struct that wraps an element and a pointer to the next node
  4. Cons(u32, Box<List>),
  5. // Nil: A node that signifies the end of the linked list
  6. Nil,
  7. }
  8. // Methods can be attached to an enum
  9. impl List {
  10. // Create an empty list
  11. fn new() -> List {
  12. // `Nil` has type `List`
  13. Nil
  14. }
  15. // Consume a list, and return the same list with a new element at its front
  16. fn prepend(self, elem: u32) -> List {
  17. // `Cons` also has type List
  18. Cons(elem, Box::new(self))
  19. }
  20. // Return the length of the list
  21. fn len(&self) -> u32 {
  22. // `self` has to be matched, because the behavior of this method
  23. // depends on the variant of `self`
  24. // `self` has type `&List`, and `*self` has type `List`, matching on a
  25. // concrete type `T` is preferred over a match on a reference `&T`
  26. match *self {
  27. // Can't take ownership of the tail, because `self` is borrowed;
  28. // instead take a reference to the tail
  29. Cons(_, ref tail) => 1 + tail.len(),
  30. // Base Case: An empty list has zero length
  31. Nil => 0
  32. }
  33. }
  34. // Return representation of the list as a (heap allocated) string
  35. fn stringify(&self) -> String {
  36. match *self {
  37. Cons(head, ref tail) => {
  38. // `format!` is similar to `print!`, but returns a heap
  39. // allocated string instead of printing to the console
  40. format!("{}, {}", head, tail.stringify())
  41. },
  42. Nil => {
  43. format!("Nil")
  44. },
  45. }
  46. }
  47. }
  48. fn main() {
  49. // Create an empty linked list
  50. let mut list = List::new();
  51. // Prepend some elements
  52. list = list.prepend(1);
  53. list = list.prepend(2);
  54. list = list.prepend(3);
  55. // Show the final state of the list
  56. println!("linked list has length: {}", list.len());
  57. println!("{}", list.stringify());
  58. }

See also:

Box and methods