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
- A
traitdeclares method signatures. impl Summary for Articleprovides them.- The method is then callable on the type.
Keywords and builtins used here
ArticleStringfnforimplletmainselfstructsummarizetrait
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.
Step 1 of 3 in Traits, step 1 of 19 in Traits & generics.