typestar

Traits in Rust

Shared behavior a type can implement.

trait Summary {
    fn summarize(&self) -> String;
}

struct Article {
    title: String,
}

impl Summary for Article {
    fn summarize(&self) -> String {
        format!("Read more: {}", self.title)
    }
}

fn main() {
    let a = Article { title: String::from("Typing") };
    println!("{}", a.summarize());
}

How it works

  1. A trait declares method signatures.
  2. impl Summary for Article provides them.
  3. The method is then callable on the type.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
281
Tokens
83
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 50 seconds.

Type this snippet

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

Next →