src/std-traits/default.md
Default TraitThe Default trait produces a default value for a type.
# // Copyright 2023 Google LLC
# // SPDX-License-Identifier: Apache-2.0
#
#[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();
dbg!(default_struct);
let almost_default_struct =
Derived { y: "Y is set!".into(), ..Derived::default() };
dbg!(almost_default_struct);
let nothing: Option<Derived> = None;
dbg!(nothing.unwrap_or_default());
}
#[derive(Default)].Default too.Default with reasonable values (e.g.
0, "", etc).Default and
provides convenience methods that use it... syntax is called struct update syntax.