Rust

A safe, concurrent, practical language

  • Say hello to rust
  • Ownership
    • Reference & Borrowing
  • Lifetimes

Agenda

Modules Collections Error Handling
Generics Closures Pointers
Build System Concurrency Pointers
Say Hello to rust
						
fn main() {
    println!("Hello, world!");
}

						
					
Every rust program has a main function
						
fn main() {

}
						
					
Macros
						
println!("Hello, world!");
						
					

Let's run the hello world.

Immutability

Everything variable in rust is immutable by default

Ownership

Stack and heap

Ownership Rules

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

Ownership

						
fn main() {
    let x = String::from("hi");
    println!("x is {}", x);
    let y = x;
    println!("x is {}", x);
}
						
					

Doesn't compile

Why does this work?

Ownership and Functions

						
fn main() {
    let mut x = String::from("hello");
    println!("x is {}", x);
    concat_world(x);
    println!("x is {}", x);
}

fn concat_world(mut x : String){
    x.push_str("world");
}
						
					

Borrow

Return ownership once done

						
fn main() {
    let mut x = String::from("hello");
    println!("x is {}", x);
    let (isHello, x) = is_string_hello(x);
    println!("x is {} and isHello is {}", x, isHello);
}

fn is_string_hello(mut x : String) -> (bool, String) {
    return (x.eq("hello"), x);
}
						
					

References

Pass reference

						
fn main() {
    let mut x = String::from("hello");
    println!("x is {}", x);
    let isHello = is_string_hello(&x);
    println!("x is {} and isHello is {}", x, isHello);
}

fn is_string_hello(x : &String) -> bool {
    return x.eq("hello");
}
						
					

Modifying a reference

						
fn main() {
    let mut x = String::from("hello");
    concat_hello(&x);
    println!("x is {}", x);
}

fn concat_hello(x : &String){
    return x.push_str("hello");
}
						
					

Mutable references

						
fn main() {
    let mut x = String::from("hello");
    concat_hello(&mut x);
    println!("x is {}", x);
}

fn concat_hello(x : &mut String){
    return x.push_str("hello");
}
						
					

Lifetimes

Dangling pointers

							
int *c = malloc(sizeof(int));
free(c);
*c = 3; //writing to freed location!
							
						

Borrow Checker

						
{
    let r;

    {
        let x = 5;
        r = &x;
    }

    println!("r: {}", r);
}
						
					

Lifetimes

						
{
    let r;         // -------+-- 'a
                   //        |
    {              //        |
        let x = 5; // -+-----+-- 'b
        r = &x;    //  |     |
    }              // -+     |
                   //        |
    println!("r: {}", r); // |
                   //        |
                   // -------+
}
						
					

Summary

Ownership : To free memory

Lifetimes : To prevent dangling pointers