39 lines
775 B
Rust
39 lines
775 B
Rust
|
|
enum List {
|
|
Cons(u32, Box<List>),
|
|
Nil,
|
|
}
|
|
|
|
impl List {
|
|
fn new() -> List {
|
|
List::Nil
|
|
}
|
|
|
|
fn prepend(self, element: u32) -> List {
|
|
List::Cons(element, Box::new(self))
|
|
}
|
|
|
|
fn len(&self) -> u32 {
|
|
match *self {
|
|
List::Nil => 0_u32,
|
|
List::Cons(_, ref next) => 1 + next.len(),
|
|
}
|
|
}
|
|
|
|
fn stringify(&self) -> String {
|
|
match *self {
|
|
List::Nil => format!("Nil"),
|
|
List::Cons(this, ref next) => format!("{} -> {}", this, next.stringify()),
|
|
}
|
|
}
|
|
}
|
|
|
|
fn main() {
|
|
let mut list = List::new();
|
|
list = list.prepend(1);
|
|
list = list.prepend(2);
|
|
list = list.prepend(3);
|
|
|
|
println!("Len: {}", list.len());
|
|
println!("Str: {}", list.stringify());
|
|
} |