Rápida Introdução ao Rust

Me

História

  • Criada em 2006 por Graydon Hoare.
  • Patrocinada pela Mozilla em 2009.
  • Versão 1.0 em 2015.
  • Versão atual: 1.35
  • Objetivo: Criar uma linguagem rápida mas com seguraça de memória.

História

Basic (com números e estruturado), dBase III Plus, Clipper, Pascal, Cobol, Delphi (ObjectPascal), C, C++, ActionScript (Flash), PHP, JavaScript, Python, Objective-C, Clojure, Java, Scala, Rust.

(Lisp, Haskell, Ruby)
A language that doesn't affect the way you think about programming, is not worth knowing.
-- Alan Perlis, "ALGOL"

Meu Primeiro Rust


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

Meu Primeiro Rust

Tempo para gerar esse código:

0 segundos

<<<<<<< Updated upstream

cargo init

=======

cargo init

>>>>>>> Stashed changes

Cargo

"Cargo is the Rust package manager"

"Cargo downloads your Rust package’s dependencies, compiles your packages, makes distributable packages, and uploads them to crates.io, the Rust community’s package registry."

De Volta Ao Rust - Static Typed


fn main() {
    let a: u8 = 2;
    println!("{}", a);
}
                        

Mas De Volta Ao Rust


fn main() {
    let a = 2u8;
    println!("{}", a);
}
                        

Mas De Volta Ao Rust


fn main() {
    let a = 2;
    println!("{}", a);
}
                        

De Volta ao Rust - Pattern Matching


fn factorial(i: u64) -> u64 {
    match i {
        0 => 1,
        n => n * factorial(n-1)
    }
}
                        

De Volta ao Rust - Returns are not necessary


fn is_pred(i: u64) -> Bool {
    if i % 2 == 0 {
       True
    } else {
       False
    }
}
                        

De Volta ao Rust - Returns are not necessary


fn is_pred(i: u64) -> Bool {
    i % 2 == 0
}
                        

De Volta ao Rust - Enums


enum IPAddr {
    IPV4,
    IPV6
}
                        

Mas De Volta ao Rust


enum IPAddr {
    IPV4(String),
    IPV6(String)
}
                        

Mas De Volta ao Rust


let home = IpAddr::IPV4(String::from("127.0.0.1");

match home {
    IPV4(ipv4_address) => println!("IPv4 addr: {}", ipv4_address),
    IPV6(ipv6_address) => println!("Ipv6 addr: {}", ipv6_address),
}
                        

De Volta ao Rust - No OO

No OO


struct MyStruct {
    a_field: String,
    r_a: [2u64; 10],
}
                        

No OO - But "functions in structs"


impl MyStruct {
    fn first_element(&self) -> u64 {
        self.r_a.get(0)
    }
}
                        

No OO - But Traits


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

No OO - But Traits


impl Summarize for MyStruct {
    fn summarize(&self) -> String {
        self.a_field
    }
}
                        

No OO - But Generics


fn make_summary<T>(summarizable: T) {
    T.summarize()
}
                        

No OO - But Generic Traits


fn make_summary<T>(summarizable: T)
    where T: Summarize
{
    T.summarize()
}
                        

E Aquela "Segurança de Memória"?

1. No Null Pointers


fn may_not_exist(value: Option<String>) {
    match value {
        Some(the_string) => println!("I got a string! {}", the_string),
        None => println!("I got nothing")
    }
}
                        

2. No Shared Memory


fn main() {
   let a = String::from("A reference to a string in the code section copied to the stack");
   let b = a;
   println!("The string is: {}", a);
}
                        

2. No Shared Memory


fn main() {
   let a = String::from("A reference to a string in the code section copied to the stack");
   let b = &a;
   println!("The string is: {}", a);
}
                        
presente := Presente { ... }
canal <- presente
 
presente := Presente { ... }
canal <- presente
presente.abrir()

3. Immutable variables by default


fn main() {
    let a = 3;
    a = 5;
}
                        

Error Control


enum Result<T, E> {
    Ok(T),
    Err(E),
}
                        

match File::create("something.txt") {
    Ok(fp) => fp.write_all(b"Hello world"),
    Err(err) => println!("Failure! {}", err),
}
                        

Compilador Chato mas Amigável


fn main() {
    let a = 2;
    a = 3;
    println!("{}", a);
}
                        

3 |     let a = 2;
  |         -
  |         |
  |         first assignment to `a`
  |         help: make this binding mutable: `mut a`
4 |     a = 3;
  |     ^^^^^ cannot assign twice to immutable variable
                        

3 |     let a = 2;
  |         -
  |         |
  |         first assignment to `a`
  |         help: make this binding mutable: `mut a`
4 |     a = 3;
  |     ^^^^^ cannot assign twice to immutable variable
                        

3 |     let a = 2;
  |         -
  |         |
  |         first assignment to `a`
  |         help: make this binding mutable: `mut a`
4 |     a = 3;
  |     ^^^^^ cannot assign twice to immutable variable
                        

A linguagem mais amada segundo o StackOverflow Survey 2019

... pelo 4⁰ ano seguido.

4.5k issues no Github

E agora?