Rust 101

But not really.

Disclaimer!

This is a very high-level presentation. There will be a handful of links at the end.

Installation

Just use rustup. It's like nvm for Rust.

Examples

Because we have to learn somehow.

Control flow

fn main() {
    let number = 6;

    if number % 3 == 0 {
        println!("number is divisible by 3");
    } else if number % 2 == 0 {
        println!("number is divisible by 2");
    } else {
        println!("number is not divisible by 3, or 2");
    }
}

Control flow

fn main() {
    let condition = true;
    let number = if condition { 5 } else { 6 };

    println!("The value of number is: {}", number);
}

Control flow

fn main() {
    let mut counter = 0;

    let result = loop {
        counter += 1;

        if counter == 10 {
            break counter * 2;
        }
    };

    println!("The result is {}", result);
}

Control flow

fn main() {
    let a = [10, 20, 30, 40, 50];
    let mut index = 0;

    while index < 5 {
        println!("the value is: {}", a[index]);

        index += 1;
    }
}

Control flow

fn main() {
    let a = [10, 20, 30, 40, 50];

    for element in a {
        println!("the value is: {}", element);
    }
}

Functions

fn is_divisible_by(lhs: u32, rhs: u32) -> bool {
    if rhs == 0 {
        // Early return.
        return false;
    }

    // No `return` not `;` here!
    lhs % rhs == 0
}

Functions

fn  add_one_v1   (x: u32) -> u32 { x + 1 }
let add_one_v2 = |x: u32| -> u32 { x + 1 };
let add_one_v3 = |x|             { x + 1 };
let add_one_v4 = |x|               x + 1  ;

Functions

let sum_of_squared_odd_numbers: u32 = (0..)
    .map(|n| n * n)
    .take_while(|&n_squared| n_squared < limit)
    .filter(|&n_squared| n % 2 == 1)
    .fold(0, |sum, n_squared| sum + n_squared);

Pattern matching

enum Coin {
    Penny,
    Nickel,
    Dime,
    Quarter,
}

fn value_in_cents(coin: Coin) -> u8 {
    match coin {
        Coin::Penny => 1,
        Coin::Nickel => 5,
        Coin::Dime => 10,
        Coin::Quarter => 25,
    }
}

Structs

struct Tweet {
    username: String,
    content: String,
    reply: bool,
    retweet: bool,
    retweets: u32,
}

Traits

trait Summary {
    fn summarize(&self) -> String;
}

impl Summary for Tweet {
    fn summarize(&self) -> String {
        format!("{}: {}", self.username, self.content)
    }
}

// Later
tweet.summarize()

Ownership

Ownership is Rust’s most unique feature and has deep implications for the rest of the language. It enables Rust to make memory safety guarantees without needing a garbage collector, so it’s important to understand how ownership works.

Ownership

  1. Each value in Rust has a variable that’s called its owner.
  2. There can only be one owner at a time.
  3. When the owner goes out of scope, the value will be dropped.

Ownership

Ownership

Ownership

Questions?

Links

Rust 101

By Radosław Miernik

Rust 101

  • 651