📊 Capítulo 13: Traits & Generics
Especialização em Sistemas com Rust
🗺️ Polimorfismo Estático (Monomorphization) vs Dinâmico (Trait Objects)
flowchart TD
POLY{"Tipo de Polimorfismo"}
POLY --> |"Estático: fn exibir<T: Display>(item: T)"| STATIC["Monomorphization (Compilação gera 1 função especializada para cada tipo / Zero Overhead)"]
POLY --> |"Dinâmico: fn exibir(item: &dyn Display)"| DYN["Trait Objects (Vtable Pointer / Despacho Dinâmico em tempo de execução)"]
style POLY fill:#ede7f6,stroke:#512da8,stroke-width:2px
style STATIC fill:#e8f5e9,stroke:#4caf50,stroke-width:2px
style DYN fill:#fff3e0,stroke:#ff9800,stroke-width:1.5px
🎯 Slide 1: Definindo e Implementando Traits
pub trait Serializavel {
fn para_json(&self) -> String;
// Método com implementação padrão (default method)
fn versao(&self) -> &str {
"v1.0"
}
}
🎯 Slide 2: Trait Bounds & Cláusula where
fn processar_dados<T, U>(item1: T, item2: U) -> String
where
T: Display + Clone,
U: Debug + PartialEq,
{
format!("{}: {:?}", item1, item2)
}
- Torna as assinaturas genéricas complexas limpas e legíveis.
🎯 Slide 3: Traits Padrão Deriváveis (#[derive])
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]: O compilador gera centenas de linhas de implementação automática de infraestrutura!
Slide 1 de 1
Atalhos: ← → Navegar • Espaço Avançar • F Tela Cheia • Home Início • End Fim