Introduction to Rust:

a modern programming language

@i_Genius

Eugenio Petullà

    Mozilla Tech Speaker

    Full Stack Developer

    Open Source Aholic

Back to the time...

    2009 - Graydon Hoare

    2010 - Mozilla adoption

    2012 - First release of the compiler

    2015 - First stable realese (1.0)

    2016 - Most Loved Language for StackOverflow

StackOverflow 2016

What is Rust?

Rust is a systems programming language focused on three goals: safety, speed, and concurrency.

What is included?

    Stack allocation of structures

    Pointers into stack memory

    Threads with shared memory

What is not included?

    No dangling pointers

    No memory leaks

    No data races

Memory allocation

It doesn't need a runtime nor a garbage collector

    Can be used to write kernels and embedded code

    You never get the dangers of a garbage collector kicking in at inopportune times

    It can integrate with other languages that do need their own runtimes (like JavaScript)

You can link with C

So... is it possile transform it into unsafe code??

Obvously NO!

You can use some unsafe features but they are clearly marked and isolated from the rest of the code

Rust compiler is rustc

...and it's written in Rust itself!

Cargo Package Manager

It's also a complete project manager!

Crates and Modules

crates.io

How it works


	$ cargo new hello_world --bin
	            	

	$ cd hello_world
	$ tree .
	.
	├── Cargo.toml
	└── src
	    └── main.rs

	1 directory, 2 files
					

Cargo.toml


	[package]
	name = "hello_world"
	version = "0.1.0"
	authors = ["Your Name <you@example.com>"]
            		

This is called a manifest, and it contains all of the metadata that Cargo needs to compile your project.

src/main.rs


    fn main() {
    	println!("Hello, world!");
	}
            		

Build it and run it...


    $ cargo build
   Compiling hello_world v0.1.0 (file:///path/hello_world)
   					

    $ ./target/debug/hello_world
	Hello, world!
   					

... or directly run it!


    $ cargo run
    Fresh hello_world v0.1.0 (file:///path/hello_world)
	Running `target/hello_world`
	Hello, world!
   					

Rust Syntax

Variable Bindings

Functions

Conditional

Loops

Structs

Match

Variables

Are unmutable by default


	let var_name = 4;
            		

Variables

Can be mutable by declaration


	let mut var_name = other_var;
            		

Variables

Scope and shadowing


let x: i32 = 8;
	{
	    println!("{}", x); // Prints "8"
	    let x = 12;
	    println!("{}", x); // Prints "12"
	}
println!("{}", x); // Prints "8"
let x =  42;
println!("{}", x); // Prints "42"
            		

Functions

Passing a value


fn main() {
    print_sum(3, 4);
}

fn print_sum(x: i32, y: i32) {
    println!("sum is: {}", x + y);
}
            		

Functions

Returing a value


fn add_one(x: i32) -> i32 {
    x + 1 // No semicolons needed here!
}
            		

Expressions vs. Statements

Rust is primarily an expression-based language. There are only two kinds of statements, and everything else is an expression.

Early returns


fn foo(x: i32) -> i32 {
    return x;

    // we never run this code!
    x + 1
}
            		

fn foo(x: i32) -> i32 {
    return x + 1; // Buhh, poor style!
}
            		

Conditional

The if statement


let x = 5;

let y = if x == 5 { 10 } else { 15 }; // y: i32
            		

if is an expression. The value of the expression is the value of the last expression in whichever branch was chosen.

Loops

Infinite loop


loop {
    println!("Loop forever!");
}
            		

Loops

while loop


let mut x = 5; // mut x: i32
let mut done = false; // mut done: bool

while !done {
    x += x - 3;

    println!("{}", x);

    if x % 5 == 0 {
        done = true;
    }
}
            		

Loops

for loop


// C-Style
for (x = 0; x < 10; x++) {
    printf( "%d\n", x );
}

// Rust Style
for x in 0..10 {
    println!("{}", x); // x: i32
}
            		

Loops

On ranges


for (index, value) in (5..10).enumerate() {
    println!("index = {} and value = {}", index, value);
}
            		

...will output


index = 0 and value = 5
index = 1 and value = 6
index = 2 and value = 7
index = 3 and value = 8
index = 4 and value = 9
            		

Loops

On iterators


let lines = "hello\nworld".lines();

for (linenumber, line) in lines.enumerate() {
    println!("{}: {}", linenumber, line);
}
            		

...will output


0: hello
1: world

            		

Loops

Break the iteration


let mut x = 5;

loop {
    x += x - 3;

    println!("{}", x);

    if x % 5 == 0 { break; }
}
            		

Loops

Continue


for x in 0..10 {
    if x % 2 == 0 { continue; }

    println!("{}", x);
}
            		

Structs

Combine more variables in a single, unified datatype


struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let origin = Point { x: 0, y: 0 }; // origin: Point

    println!("The origin is at ({}, {})", origin.x, origin.y);

}            		

Match

Matching and cases


let x = 1;

match x {
	0 => println!("Zero"),
	1 => println!("One"),
	2 => println!("Two"),
	3 => println!("Three"),
	4 => println!("Four"),
	5 => println!("Five"),
	_ => println!("Six or more!"),
}
            		

Match

Easy type conversion (to string)


let x = 1;

let number = match x {
	0 => "0",
	1 => "One",
	2 => "Two",
	3 => "Three",
	4 => "4",
	5 => "5",
	_ => "Six or more!",
}
            		

Learn by Example

Guessing game!

Include Library


extern crate rand;

use std::io;
use std::cmp::Ordering;
use rand::Rng;
            		


fn main() {
    println!("Guess a number between 1 and 100!");
    let secret_number = rand::thread_rng().gen_range(1, 101);

    loop {
        println!("Please input your guess.");
        let mut guess = String::new();

        io::stdin().read_line(&mut guess)
            .expect("failed to read line");

        let guess: u32 = match guess.trim().parse() {
            Ok(num) => num,
            Err(_) => continue,
        };
        println!("You guessed: {}", guess);

        match guess.cmp(&secret_number) {
            Ordering::Less    => println!("Too small!"),
            Ordering::Greater => println!("Too big!"),
            Ordering::Equal   => {
                println!("You win!");
                break;
            }
        }
    }
}
            		

Labirintite

Maze generator in Rust

github.com/EugenioPetulla/labirintite-in-rust

Actual obstacles

No Pain, No Gain!

Actual obstacles

    1 on 4: learning curve

    1 on 7: lack of libraries

    1 on 9: general “maturity” concerns

    1 on 19: lack of IDEs (1 on 4 non-users)

    1 on 20: compiler performance

Rust Roadmap

github.com/rust-lang/rust-roadmap

Rust Roadmap

    Have a lower learning curve

    Have a pleasant edit-compile-debug cycle

    Provide a solid, but basic IDE experience

    Provide easy access to high quality crates

    Be well-equipped for writing robust, high-scale servers

    Have 1.0-level crates for essential tasks

    Integrate easily into large build systems

    Rust's community should provide mentoring

Rust Roadmap

Areas of Exploration

    Integration with other languages
    running the gamut from C to JavaScript

    Usage in resource-constrained environments

Rust Community

Grazie

Eugenio Petullà

Mozilla Tech Speaker

eugeniopetulla.github.io/Introduction-to-Rust