Pop quiz: How many bits in a C `long double`?
fn fizzbuzz(num: uint) -> String {
match (num % 3, num % 5) {
(0, 0) => "FizzBuzz".to_string(),
(0, _) => "Fizz".to_string(),
(_, 0) => "Buzz".to_string(),
(_, _) => num.to_string()
}
}
fn main() -> () {
for num in range(0u, 101) {
println!("{}", fizzbuzz(num));
}
}
struct Dog {
name: String,
age: uint,
}
impl Dog {
fn new(name: String, age: uint) -> Dog {
Dog {name:name, age:age}
}
fn bark(&self) -> String {
format!("I am dog {}. I am {}", self.name, self.age)
}
}
fn main() -> () {
let hunter_dawg: Dog = Dog::new("Hunter".to_string(), 5);
println!("{}", hunter_dawg.bark()) // See no ;
}
enum Option<T> {
Some(T),
None
}
enum Result<T, E> {
Ok(T),
Err(E)
}
#[deriving(Show)]
enum List<T> {
Nil,
Cons(T, Box<List<T>>),
}
fn main() {
let list: List<i32> = Cons(1i32, box Cons(2, box Cons(3, box Nil)));
println!("{}", list);
}
// This function takes ownership of the heap allocated memory
fn destroy_box(c: Box<int>) {
// Have to return it to be claimed again.
println!("destroying a box that contains {}", c);
// `c` will be destroyed in this scope, and the memory will be freed
}
fn borrow_variable<T: std::fmt::Show>(d: &T) {
// Do not have to return the variable to let the caller reclaim it
println!("variable, {} is borrowed!", d);
}
fn borrow_mut_variable(f: &mut f64) {
*f = 42.0;
}
fn main() {
for i in range(0u,500) {
spawn(proc() {
println!("Hello, {}!", i);
});
}
}
http://is.gd/TMCqCN
Explicit lifetimes to keep track of references
struct Pair<'a, 'b> {
one: &'a mut int,
two: &'b mut int,
}
fn main() {
let mut one = 1; //lifetime of 'o
{
let mut two = 2; //lifetime of 't, shorter because in block ('t < 'o)
println!("Before: ({}, {})", one, two);
// `Pair` gets specialized for `'a = 'o` and `'b = 't`
let pair = Pair { one: &mut one, two: &mut two };
*pair.one = 2;
*pair.two = 1;
println!("After: ({}, {})", pair.one, pair.two);
}
}