← Volver al curso: Rust desde cero

Traits: comportamiento compartido

Vídeo próximamente

Un trait describe un comportamiento que varios tipos pueden tener en común: "todo lo que se puede dibujar", "todo lo que se puede comparar", "todo lo que se puede convertir en texto". Es parecido a una interfaz en Java o C#, aunque con diferencias que verás en esta lección. Los traits son la base de casi toda la biblioteca estándar: println! usa Display y Debug, == usa PartialEq, y los bucles for usan Iterator. Entenderlos desbloquea el resto del lenguaje.

Definir e implementar un trait

Se declara con trait y una lista de firmas de métodos. Cada tipo lo implementa con impl Trait for Tipo. Un trait puede ofrecer una implementación por defecto en algunos métodos, que los tipos pueden usar tal cual o sobrescribir. Un detalle importante, llamado regla del huérfano: solo puedes implementar un trait para un tipo si tu crate define el trait o define el tipo. No puedes implementar Display para Vec<i32>, porque ni uno ni otro son tuyos.

rust
trait Animal {
    fn name(&self) -> String;
    fn sound(&self) -> String;

    // default implementation
    fn speak(&self) -> String {
        format!("{} says {}", self.name(), self.sound())
    }
}

struct Dog;
struct Cat {
    lives: u8,
}

impl Animal for Dog {
    fn name(&self) -> String { String::from("Dog") }
    fn sound(&self) -> String { String::from("woof") }
}

impl Animal for Cat {
    fn name(&self) -> String { format!("Cat ({} lives)", self.lives) }
    fn sound(&self) -> String { String::from("meow") }
    fn speak(&self) -> String { format!("{} purrs", self.name()) } // override
}

fn main() {
    println!("{}", Dog.speak());
    println!("{}", Cat { lives: 9 }.speak());
}

Traits como parámetros

Hay dos formas de decir "acepto cualquier tipo que implemente este trait". La sintaxis impl Trait en los parámetros (fn show(a: &impl Animal)) es la más corta. La sintaxis con límite de trait (fn show<T: Animal>(a: &T)), que estudiarás mejor en la próxima lección sobre genéricos, es equivalente y más flexible. En ambos casos el compilador genera código específico para cada tipo concreto (despacho estático), sin coste en ejecución. Puedes exigir varios traits a la vez con +, por ejemplo T: Animal + Debug.

rust
use std::fmt;

trait Describe {
    fn describe(&self) -> String;
}

struct Point { x: i32, y: i32 }

impl Describe for Point {
    fn describe(&self) -> String { format!("point at {}, {}", self.x, self.y) }
}
impl Describe for i32 {
    fn describe(&self) -> String { format!("the number {}", self) }
}

impl fmt::Display for Point {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "({}, {})", self.x, self.y)
    }
}

fn print_it(item: &impl Describe) {
    println!("{}", item.describe());
}

fn print_both<T: Describe + fmt::Display>(item: &T) {
    println!("{} / {}", item, item.describe());
}

fn main() {
    print_it(&42);
    print_it(&Point { x: 1, y: 2 });
    print_both(&Point { x: 3, y: 4 });
}

Objetos trait: dyn Trait

A veces necesitas guardar valores de tipos distintos en la misma colección, por ejemplo una lista de animales variados. Un Vec<T> exige un solo T, así que usas un objeto trait: Vec<Box<dyn Animal>>. Box pone cada valor en el montón, y dyn indica "algún tipo que implementa Animal, decidido en ejecución" (despacho dinámico). El coste es una pequeña indirección al llamar a los métodos. Úsalo cuando necesites mezclar tipos; si todos son iguales o los conoces al compilar, prefiere genéricos.

rust
trait Shape {
    fn area(&self) -> f64;
}

struct Square(f64);
struct Circle(f64);

impl Shape for Square {
    fn area(&self) -> f64 { self.0 * self.0 }
}
impl Shape for Circle {
    fn area(&self) -> f64 { 3.14159 * self.0 * self.0 }
}

fn main() {
    let shapes: Vec<Box<dyn Shape>> = vec![Box::new(Square(2.0)), Box::new(Circle(1.0))];
    let total: f64 = shapes.iter().map(|s| s.area()).sum();
    println!("total area = {:.2}", total);
}

Un último punto: los traits también permiten devolver tipos sin nombrarlos con impl Trait en el retorno, algo muy usado con iteradores y closures, que verás en la semana 7. Y los traits más importantes de la biblioteca estándar merecen conocerse por nombre: Display para mostrar al usuario, Debug para depurar, Clone para duplicar, Default para el valor inicial, From e Into para convertir y Drop para ejecutar código al liberar un valor. Cuando diseñes tus tipos, implementar estos traits hace que tus datos se integren con el resto del ecosistema sin esfuerzo.

rust
trait Greeter {
    fn greet(&self) -> String;
    fn shout(&self) -> String {
        self.greet().to_uppercase()
    }
}

struct English { name: String }
struct Spanish { name: String }

impl Greeter for English {
    fn greet(&self) -> String { format!("Hello, {}!", self.name) }
}
impl Greeter for Spanish {
    fn greet(&self) -> String { format!("Hola, {}!", self.name) }
}

fn main() {
    let all: Vec<Box<dyn Greeter>> = vec![
        Box::new(English { name: String::from("Ana") }),
        Box::new(Spanish { name: String::from("Luis") }),
    ];
    for g in &all {
        println!("{} / {}", g.greet(), g.shout());
    }
}

Pon a prueba lo aprendido

Pregunta 1 de 4

¿Qué es un trait?

✎ Mis apuntes

Guardado solo en este navegador. Inicia sesión para tenerlo en tu cuenta.0/5000 caracteres

← AnteriorSiguiente →