El trait Default

El trait Default produce un valor predeterminado para un tipo.

#[derive(Debug, Default)]
struct Derived {
    x: u32,
    y: String,
    z: Implemented,
}

#[derive(Debug)]
struct Implemented(String);

impl Default for Implemented {
    fn default() -> Self {
        Self("John Smith".into())
    }
}

fn main() {
    let default_struct = Derived::default();
    println!("{default_struct:#?}");

    let almost_default_struct =
        Derived { y: "Ya está configurado.".into(), ..Derived::default() };
    println!("{almost_default_struct:#?}");

    let nothing: Option<Derived> = None;
    println!("{:#?}", nothing.unwrap_or_default());
}
This slide should take about 5 minutes.
  • Se puede implementar directamente o se puede derivar a través de #[derive(Default)].
  • Una implementación derivada producirá un valor en el que todos los campos tendrán sus valores predeterminados.
    • Esto significa que todos los tipos de la estructura también deberán implementar Default.
  • Los tipos estándar de Rust suelen implementar Default con valores razonables (por ejemplo, 0, "", etc.).
  • The partial struct initialization works nicely with default.
  • The Rust standard library is aware that types can implement Default and provides convenience methods that use it.
  • The .. syntax is called struct update syntax.