# Referência Rápida de Rust

*Ownership, tipos, traits, correspondência de padrões*

> Source: The Rust Programming Language (doc.rust-lang.org) · MIT

## Básico

### Hello World

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

### Comandos Cargo

```
cargo new my_project    # create new project
cargo build             # compile (debug)
cargo build --release   # compile (optimized)
cargo run               # build and run
cargo test              # run tests
```

### Estrutura do Projeto

| Command | Description |
|---------|-------------|
| `Cargo.toml` | Manifesto do projeto (dependências, metadados) |
| `src/main.rs` | Ponto de entrada do crate binário |
| `src/lib.rs` | Raiz do crate de biblioteca |
| `tests/` | Diretório de testes de integração |

## Variáveis e Mutabilidade

### Binding e Mutabilidade

```
let x = 5;              // immutable by default
let mut y = 10;         // mutable
y += 1;
const MAX: u32 = 100;   // compile-time constant
```

### Shadowing

```
let x = 5;
let x = x + 1;          // shadows previous x
let x = "now a string"; // can change type
```

### Tipos Escalares

| Command | Description |
|---------|-------------|
| `i8..i128, isize` | Inteiros com sinal |
| `u8..u128, usize` | Inteiros sem sinal |
| `f32, f64` | Ponto flutuante (f64 padrão) |
| `bool` | `true` / `false` |
| `char` | Valor escalar Unicode (4 bytes) |

### Tipos Compostos

```
let tup: (i32, f64, char) = (42, 6.4, 'z');
let (a, b, c) = tup;        // destructure
let arr: [i32; 3] = [1, 2, 3];
let first = arr[0];
```

## Funções

### Definição

```
fn add(a: i32, b: i32) -> i32 {
    a + b   // no semicolon = return expression
}
```

### Closures

```
let double = |x: i32| x * 2;
let sum: i32 = vec![1, 2, 3]
    .iter()
    .map(|x| x * 2)
    .sum();
```

### Ponteiros de Função e Traits

| Command | Description |
|---------|-------------|
| `fn(T) -> U` | Tipo de ponteiro de função |
| `Fn(T) -> U` | Closure que empresta |
| `FnMut(T) -> U` | Closure que empresta mutavelmente |
| `FnOnce(T) -> U` | Closure que assume ownership |

## Controle de Fluxo

### If / Else

```
let status = if score >= 90 { "A" }
             else if score >= 80 { "B" }
             else { "C" };  // if is an expression
```

### Laços

```
loop { break; }                  // infinite
while condition { }              // while
for item in &vec { }             // iterator
for i in 0..10 { }              // range
for (i, v) in vec.iter().enumerate() { }
```

### Rótulos de Laço

```
'outer: for i in 0..5 {
    for j in 0..5 {
        if i + j > 6 { break 'outer; }
    }
}
```

## Ownership e Borrowing

### Regras de Ownership

> 1. Cada valor tem exatamente um dono.
2. Quando o dono sai de escopo, o valor é descartado.
3. Valores podem ser movidos ou clonados.

### Move e Clone

```
let s1 = String::from("hello");
let s2 = s1;          // s1 is moved, no longer valid
let s3 = s2.clone();  // deep copy, both valid
```

### Borrowing

```
fn len(s: &String) -> usize { s.len() }  // shared ref
fn push(s: &mut String) { s.push('!'); }  // mutable ref
// Rule: many &T OR one &mut T, never both
```

### Lifetimes

```
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
    if a.len() > b.len() { a } else { b }
}
```

## Structs e Enums

### Struct

```
struct User {
    name: String,
    age: u32,
    active: bool,
}
let u = User { name: String::from("Alice"), age: 30, active: true };
```

### Bloco Impl

```
impl User {
    fn new(name: &str, age: u32) -> Self {
        Self { name: name.to_string(), age, active: true }
    }
    fn greeting(&self) -> String {
        format!("Hi, {}", self.name)
    }
}
```

### Enums

```
enum Shape {
    Circle(f64),
    Rect { w: f64, h: f64 },
    Point,
}
let s = Shape::Circle(5.0);
```

## Correspondência de Padrões

### Expressão Match

```
match shape {
    Shape::Circle(r) => std::f64::consts::PI * r * r,
    Shape::Rect { w, h } => w * h,
    Shape::Point => 0.0,
}
```

### If Let e While Let

```
if let Some(val) = optional {
    println!("{val}");
}
while let Some(top) = stack.pop() {
    println!("{top}");
}
```

### Sintaxe de Padrões

| Command | Description |
|---------|-------------|
| `_` | Curinga, corresponde a tudo |
| `x @ 1..=5` | Vincular intervalo correspondente a `x` |
| `(a, b, ..)` | Desestruturar tupla, ignorar o resto |
| `Some(x) if x > 0` | Match guard |
| `Foo { x, .. }` | Struct, ignorar outros campos |

## Tratamento de Erros

### Result e Option

```
enum Result<T, E> { Ok(T), Err(E) }
enum Option<T>    { Some(T), None }
```

### O Operador ?

```
fn read_file(path: &str) -> Result<String, io::Error> {
    let mut s = String::new();
    File::open(path)?.read_to_string(&mut s)?;
    Ok(s)
}
```

### Tratando Erros

```
match result {
    Ok(val) => println!("{val}"),
    Err(e) => eprintln!("Error: {e}"),
}
let val = result.unwrap_or(0);
let val = result.unwrap_or_else(|_| default());
```

### Métodos Comuns

| Command | Description |
|---------|-------------|
| `.unwrap()` | Obter valor ou entrar em pânico |
| `.expect(msg)` | Obter valor ou entrar em pânico com mensagem |
| `.unwrap_or(default)` | Obter valor ou usar padrão |
| `.map(f)` | Transformar o valor Ok/Some |
| `.and_then(f)` | Encadear operações (flatmap) |
| `.is_ok() / .is_some()` | Verificação booleana |

## Traits

### Definindo e Implementando

```
trait Summary {
    fn summarize(&self) -> String;
    fn preview(&self) -> String {   // default impl
        format!("{}...", &self.summarize()[..20])
    }
}
impl Summary for User {
    fn summarize(&self) -> String { self.name.clone() }
}
```

### Trait Bounds

```
fn notify(item: &impl Summary) { }
fn notify<T: Summary + Display>(item: &T) { }
fn notify(item: &(impl Summary + Display)) { }
```

### Traits Comuns

| Command | Description |
|---------|-------------|
| `Display` | Formatação de string para usuário final |
| `Debug` | Formatação de debug (`{:?}`) |
| `Clone, Copy` | Duplicação (profunda / bit a bit) |
| `PartialEq, Eq` | Comparação de igualdade |
| `PartialOrd, Ord` | Comparação de ordem |
| `Iterator` | `next()` para iteração |
| `From, Into` | Conversões de tipo |
| `Default` | Construtor de valor padrão |

## Coleções

### Vec

```
let mut v: Vec<i32> = vec![1, 2, 3];
v.push(4);
v.pop();              // returns Option<i32>
let first = &v[0];   // panics if empty
let first = v.get(0); // returns Option<&i32>
```

### HashMap

```
use std::collections::HashMap;
let mut m = HashMap::new();
m.insert("key", 42);
m.entry("key").or_insert(0);
if let Some(val) = m.get("key") { }
```

### String

```
let s = String::from("hello");
let s = "hello".to_string();
let combined = format!("{} {}", s, "world");
for c in s.chars() { }   // iterate characters
```

### Iteradores

```
let sum: i32 = vec![1, 2, 3].iter().sum();
let doubled: Vec<_> = v.iter().map(|x| x * 2).collect();
let evens: Vec<_> = v.iter().filter(|x| *x % 2 == 0).collect();
```

## Concorrência

### Threads

```
use std::thread;
let handle = thread::spawn(|| {
    println!("from spawned thread");
});
handle.join().unwrap();
```

### Canais

```
use std::sync::mpsc;
let (tx, rx) = mpsc::channel();
tx.send(42).unwrap();
let val = rx.recv().unwrap();
```

### Estado Compartilhado

| Command | Description |
|---------|-------------|
| `Arc<T>` | Contagem de referências atômica (Rc seguro para threads) |
| `Mutex<T>` | Exclusão mútua, travar para acessar valor interno |
| `RwLock<T>` | Múltiplos leitores ou um escritor |
| `Send` | Trait: seguro para transferir entre threads |
| `Sync` | Trait: seguro para compartilhar referências entre threads |

## Macros e Atributos

### Macros Comuns

| Command | Description |
|---------|-------------|
| `println!()` | Imprimir com nova linha |
| `format!()` | Retornar String formatada |
| `vec![]` | Criar Vec a partir de literais |
| `todo!()` | Placeholder, entra em pânico em runtime |
| `assert!(expr)` | Entrar em pânico se expr for falso |
| `assert_eq!(a, b)` | Entrar em pânico se a != b |

### Atributos Derive

```
#[derive(Debug, Clone, PartialEq)]
struct Point { x: f64, y: f64 }
// Auto-implements Debug, Clone, PartialEq
```

### Atributos de Teste

```
#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn it_works() { assert_eq!(add(2, 2), 4); }
    #[test]
    #[should_panic]
    fn it_panics() { panic!("boom"); }
}
```
