Rust

... a programming language designer should be responsible for the mistakes that are made by the programmers
using the language.

[...]

It's very easy to persuade the customers of your language that everything that goes wrong is their fault and not yours. I rejected that...

- Tony Hoare

http://blog.mattcallanan.net/2010/09/tony-hoare-billion-dollar-mistake.html

Speed

Safety

Safe, Fast

  • No Data Races
  • Guaranteed memory safety
  • 0 Cost abstractions
  • Expressive

Cargo

  • build - Compile the current project
  • doc - Build this project's and its dependencies' documentation
  • new - Create a new cargo project
  • run - Build and execute src/main.rs
  • test - Run the tests
  • bench - Run the benchmarks
  • update - Update dependencies listed in Cargo.lock
  • publish - Package and upload this project to the registry

 

cargo new --bin razorrustdemo

[package]
name = "razorrustdemo"
version = "0.1.0"
authors = ["insanitybit <insanitybit@gmail.com>"]

[dependencies]
rand = "0.3.*" # Update to the latest patch version

Cargo.toml

[[package]]
name = "rand"
version = "0.3.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "libc 0.2.20 (registry+https://github.com/rust-lang/crates.io-index)",
]

Cargo.lock

extern crate rand;

fn main() {
    let rand_token: u8 = rand::random();
    println!("{:#?}", rand_token);
}
// T OR NONE
enum Option<T> {
    Some(T),
    None
}

struct Foo {
    pub bar: u64,
    baz: u64,
}

impl<T> Option<T> {
    fn of(foo: T) -> Option<T> {
       Some(foo)
    }
}
extern crate rand;

fn check_validity(name: &str) -> Option<u64> {
    if name == "admin" {
        let rand_token = rand::random();
        Some(rand_token)
    } else {
        None
    }
}

fn main() {
    match check_validity("admin") {
        Some(tok) => println!("Access granted, here's our token {:?}", tok),
        None => panic!("Invalid name"),
    }
}
fn main() {
    for i in 1..100 {
        match (i % 3 == 0, i % 5 == 0) {
            (true, true) => println!("{:?} fizzbuzz", i),
            (true, false) => println!("{:?} fizz", i),
            (false, true) => println!("{:?} buzz", i),
            (false, false) => println!("{:?}", i),
        }
    }
}
fn main() {
    let opt_foo = Some("string");
    match opt_foo {
        Some(thing) if thing.is_empty() => println!("thing is empty"),
        Some(thing) => println!("thing is {:?}", thing),
        None => println!("foo was none"),
    }
}
fn main() {
    let val = Some(rand::random());
    match val {
        Some(v) if v < 0 => println!("Negative value"),
        Some(0...10) => println!("0 to 10"),
        Some(11...100) => println!("10 to 100"),
        _ => println!(r"or whatever ¯\_(ツ)_/¯"),
    }
}
// all that other stuff from before

fn main() {
    match check_validity("admin") {
        Some(tok) => println!("Access granted, here's our token {:?}", tok),
        None => panic!("Invalid name"),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_validity_check() {
        assert!(check_validity("admin").is_some());
        assert!(check_validity("notadmin").is_none());
    }
}
pub fn check_validity(name: &str) -> Result<u64, String> {
    if name == "admin" {
        let rand_token = rand::random();
        Ok(rand_token)
    } else {
        Err(format!("Failed to authenticate user: {}", name))
    }
}

fn main() {
    match check_validity("admin") {
        Ok(tok) => println!("Access granted, here's our token {:?}", tok),
        Err(e) => panic!(e),
    }
}
extern crate rand;

/// Checks whether a username is a valid admin or not.
/// On success returns a token. On failure returns an error stirng.
///
///
/// # Arguments
///
/// * `name` - A String that represents the username to validate
///
/// # Example
/// ```
/// use razorrustdemo::validity::check_validity;
/// let username = "admin";
/// let token = check_validity(username);
/// ```
pub fn check_validity(name: &str) -> Result<u64, String> {
    if name == "admin" {
        let rand_token = rand::random();
        Ok(rand_token)
    } else {
        Err(format!("Failed to authenticate user: {}", name))
    }
}

cargo doc --open

Ownership

"Shared mutable state is the root of all evil"

struct Human {
    pub inches: u8,
    pub hair_color: String
}

fn show_height(human: Human) {
    println!("Human Height: {:?}", human.inches);
}

fn main() {
    let human = Human {inches: 70, hair_color: "brown".to_string()};

    show_height(human);
    // ERROR
    show_height(human);    
}
struct Human {
    pub inches: u8,
    pub hair_color: String
}

fn show_height(human: &Human) {
    println!("Human Height: {:?}", human.inches);
}


fn main() {
    let human = Human {inches: 70, hair_color: "brown".to_string()};

    show_height(&human);
    show_height(&human);    
}
struct Human {
    pub inches: u8,
    pub hair_color: String
}

fn show_height(human: &Human) {
    println!("Human Height: {:?}", human.inches);
}

fn main() {
    let human = Human {inches: 70, hair_color: "brown".to_string()};
    let human_ref = &mut human;

    show_height(human);
}

State Machines

Session Types

      +---------+
      | State A | <=++
      +---------+   ||
           ||       ||
           |+=======++
           ||
           \/
      +---------+
      | State B |
      +---------+
struct StateA {
    i: u64,
}

struct StateB {
    i: u64,
}

enum EitherState {
    A(StateA),
    B(StateB)
}

impl StateA {
    fn transform(self) -> EitherState {
        if self.i % 5 == 0 {
            EitherState::B(
                StateB {
                i: self.i
            })
        } else {
            EitherState::A(
                StateA {
                i: self.i + 1
            })
        }
    }
}
impl StateB {
    fn do_thing(&self) {
        println!("{:?}", self.i);
    }
}
fn main() {
    let init_state = StateA {i: 7};

    let mut new_state = init_state.transform();

    // Accessing init_state once it has transformed is a compile time error

    loop {
        match new_state {
            EitherState::A(state_a) => new_state = state_a.transform(),
            EitherState::B(state_b) => {state_b.do_thing(); break;}
        }
    }
}
                            +----------------------+
                            |connection established|
                            +----------------------+
                                       ||
                                       \/
                    +--------------------------------------+
                    |          server greeting             |
                    +--------------------------------------+
                       || (1)             || (2)       || (3)
                       \/                 ||           ||
                    +-----------------+   ||           ||
                    |Not Authenticated|   ||           ||
                    +-----------------+   ||           ||
                    || (7)   || (4)       ||           ||
                    ||       \/           \/           ||
                    ||     +----------------+          ||
                    ||     | Authenticated  |<=++      ||
                    ||     +----------------+  ||      ||
                    ||       || (7)   || (5)   || (6)  ||
                    ||       ||       \/       ||      ||
                    ||       ||    +--------+  ||      ||
                    ||       ||    |Selected|==++      ||
                    ||       ||    +--------+          ||
                    ||       ||       || (7)           ||
                    \/       \/       \/               \/
                    +--------------------------------------+
                    |               Logout                 |
                    +--------------------------------------+
                                       ||
                                       \/
                        +-------------------------------+
                        |both sides close the connection|
                        +-------------------------------+

Questions

Rust

By Colin

Rust

  • 2,292