Default in Rust
A canonical empty value, plus struct update syntax to change one field.
#[derive(Debug)]
struct Settings {
theme: String,
editor_mode: bool,
time_limit: u32,
}
impl Default for Settings {
fn default() -> Self {
Settings {
theme: "default".to_string(),
editor_mode: false,
time_limit: 60,
}
}
}
fn main() {
println!("{:?}", Settings::default());
let mine = Settings {
theme: "monokai".to_string(),
..Default::default()
};
println!("{:?}", mine);
}
How it works
#[derive(Default)]uses each field's own default.- A hand-written impl sets the values you actually want.
..Default::default()fills in the rest of a literal.
Keywords and builtins used here
DefaultSelfSettingsStringbooldefaultfalsefnforimplletmainstructu32
The run, in numbers
- Lines
- 26
- Characters to type
- 377
- Tokens
- 105
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 60 seconds.
Step 3 of 4 in Standard traits, step 10 of 19 in Traits & generics.