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