Default methods in Rust
A trait can supply behavior, so implementors only write what differs.
trait Step {
fn title(&self) -> String;
fn lines(&self) -> usize {
1
}
fn label(&self) -> String {
format!("{} ({} lines)", self.title(), self.lines())
}
}
struct Snippet;
struct Script;
impl Step for Snippet {
fn title(&self) -> String {
"Filter with WHERE".to_string()
}
}
impl Step for Script {
fn title(&self) -> String {
"config_check.rs".to_string()
}
fn lines(&self) -> usize {
84
}
}
fn main() {
println!("{}", Snippet.label());
println!("{}", Script.label());
}
How it works
- A default method may call the required ones.
- Implementors override it only when they need to.
- This is how traits stay small at the point of use.
Keywords and builtins used here
ScriptSnippetStringfnforimpllabellinesmainselfstructtitletraitusize
The run, in numbers
- Lines
- 34
- Characters to type
- 476
- Tokens
- 147
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 88 seconds.
Step 2 of 3 in Traits, step 2 of 19 in Traits & generics.