use List::*;
enum List {
// Cons: Tuple struct that wraps an element and a pointer to the next node
Cons(u32, Box<List>),
// Nil: A node that signifies the end of the linked list
Nil,
}
// Methods can be attached to an enum
impl List {
// Create an empty list
fn new() -> List {
// `Nil` has type `List`
Nil
}
// Consume a list, and return the same list with a new element at its front
fn prepend(self, elem: u32) -> List {
// `Cons` also has type List
Cons(elem, Box::new(self))
}
// Return the length of the list
fn len(&self) -> u32 {
// `self` has to be matched, because the behavior of this method
// 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`
match *self {
// Can't take ownership of the tail, because `self` is borrowed;
// instead take a reference to the tail
Cons(_, ref tail) => 1 + tail.len(),
// Base Case: An empty list has zero length
Nil => 0
}
}
// Return representation of the list as a (heap allocated) string
fn stringify(&self) -> String {
match *self {
Cons(head, ref tail) => {
// `format!` is similar to `print!`, but returns a heap
// allocated string instead of printing to the console
format!("{}, {}", head, tail.stringify())
},
Nil => {
format!("Nil")
},
}
}
}
fn test(n:usize) {
let mut p = List::new();
for _ in 1..n {
p=p.prepend(1);
}
println!("Hello, world!");
}
fn main() {
test(131028);
}
CnVzZSBMaXN0OjoqOwoKZW51bSBMaXN0IHsKICAgIC8vIENvbnM6IFR1cGxlIHN0cnVjdCB0aGF0IHdyYXBzIGFuIGVsZW1lbnQgYW5kIGEgcG9pbnRlciB0byB0aGUgbmV4dCBub2RlCiAgICBDb25zKHUzMiwgQm94PExpc3Q+KSwKICAgIC8vIE5pbDogQSBub2RlIHRoYXQgc2lnbmlmaWVzIHRoZSBlbmQgb2YgdGhlIGxpbmtlZCBsaXN0CiAgICBOaWwsCn0KCi8vIE1ldGhvZHMgY2FuIGJlIGF0dGFjaGVkIHRvIGFuIGVudW0KaW1wbCBMaXN0IHsKICAgIC8vIENyZWF0ZSBhbiBlbXB0eSBsaXN0CiAgICBmbiBuZXcoKSAtPiBMaXN0IHsKICAgICAgICAvLyBgTmlsYCBoYXMgdHlwZSBgTGlzd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