Skip to content

Instantly share code, notes, and snippets.

@bstrie
Last active January 4, 2016 01:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bstrie/8549335 to your computer and use it in GitHub Desktop.
Save bstrie/8549335 to your computer and use it in GitHub Desktop.
/* This program defines a recursive datastructure and implements methods upon it.
Recursive datastructures require a layer of indirection, which is provided here
by a unique pointer, indicated by the tilde `~` operator. These are analogous to
the C++ library type `std::unique_ptr`, though with more static safety guarantees. */
fn main() {
let list = ~Node(1, ~Node(2, ~Node(3, ~Empty)));
println!("Sum of all values in the list: {:i}.", list.multiply_by(2).sum());
}
// An `enum` defines a type that may be one of several different kinds of values at runtime.
// The type here will either contain no value, or a value and a pointer to another `IntList`.
enum IntList {
Node(int, ~IntList),
Empty
}
// An `impl` block allows methods to be defined on a type.
impl IntList {
fn sum(~self) -> int {
// As in C and C++, pointers are dereferenced with the asterisk `*` operator.
match *self {
Node(value, next) => value + next.sum(),
Empty => 0
}
}
fn multiply_by(~self, n: int) -> ~IntList {
match *self {
Node(value, next) => ~Node(value * n, next.multiply_by(n)),
Empty => ~Empty
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment