typestar

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

  1. A default method may call the required ones.
  2. Implementors override it only when they need to.
  3. This is how traits stay small at the point of use.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Traits, step 2 of 19 in Traits & generics.

← Previous Next →