github twitter email rss
Rust language
0001 Jun 1
2 minutes read

Rust language

http://doc.rust-lang.org/
http://doc.rust-lang.org/std/stability.html

Install Rust nightly(compiler) and Cargo(package & build manager)

curl -s https://static.rust-lang.org/rustup.sh | sudo sh

Simplest program

Structure

.
├── Cargo.toml
└── src
    └── main.rs

Creating, building, running with Cargo

cargo new basics --bin
cd project
cargo build
cargo run

Crates & Modules

testing

  • unit tests in crate itself
  • integration tests -> tests dir

cargo test

Language

Pattern Matching

match isOdd(x) {
  true => println("Odd"), // Notice the comma
  false => println("Even")
}
match isOdd(x) {
  true => { println("Odd"); 0 }
  false => { println("Even"); 1 }
}
let x = 4;
match x {
  0 => { ; } // Do nothing
  4 => { foo(); } 
  _ => { bar(); } // Matches every integer value
}
match x {
    3|5|6  => { println("First arm!"); }
    10..16 => { println("Second arm!"); }
    _      => { println("Default arm!"); }
}
let tup = (4, 5.0, false, "hello"); 
let (a, b, c, _) = tup;
match x {
    (x,y) if x > y => { println("Decreasing"); }
    (x,y) if y > x => { println("Increasing"); }
    _              => { println("Equal")}
}

Expressions

let foo = if x == 5 {
                "five"
          }
          else if x == 6 {
                "six"
          }
          else {
                "neither"
          }
let x = match y {
    0..9    =>  { "Less than 10" }
    _       =>  { "Greater than 10" }
}

Functions

fn foo() {
  fn bar() { println("bar"); }
  bar();
}
fn rprime_sum(x: int, y: int, m: int) {
  match (x+y)%m {
    0 => println("Multiple"),
    _ => println("Relatively prime")
  }
}

Back to posts


comments powered by Disqus