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