Created
July 6, 2015 11:06
-
-
Save kudrevatykh/54c4012096601a31ebf4 to your computer and use it in GitHub Desktop.
rust list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment