Skip to content

Instantly share code, notes, and snippets.

@nuggetnchill
Created December 22, 2021 17:37
Show Gist options
  • Select an option

  • Save nuggetnchill/0963a7a78cdd5172682bf624395ad61e to your computer and use it in GitHub Desktop.

Select an option

Save nuggetnchill/0963a7a78cdd5172682bf624395ad61e to your computer and use it in GitHub Desktop.
Traits in Rust example
//Traits in Rust: https://www.youtube.com/watch?v=T0Xfltu4h3A
pub trait Summary {
fn summarize_author(&self) -> String;
fn summarize(&self) -> String {
format!("(Read more from {}...)", self.summarize_author())
}
}
fn returns_summarizable() -> impl Summary {
Tweet {
username: String::from("@horse"),
content: String::from("I'm fast af boi"),
reply: false,
retweet: false,
}
}
pub struct NewsArticle {
pub author: String,
pub headline: String,
pub content: String,
}
impl Summary for NewsArticle {
fn summarize_author(&self) -> String {
format!("{}", self.author)
}
}
pub struct Tweet {
pub username: String,
pub content: String,
pub reply: bool,
pub retweet: bool,
}
impl Summary for Tweet {
fn summarize_author(&self) -> String {
format!("{}", self.username)
}
fn summarize(&self) -> String {
format!("{}: {}", self.username, self.content)
}
}
pub fn notify<T: Summary>(item: &T) {
println!("Breaking news! {}", item.summarize());
}
fn main() {
let article = NewsArticle {
author: String::from("YeetBoi"),
headline: String::from("West Virginia"),
content: String::from("Yeehaw my dude"),
};
println!("{}", returns_summarizable().summarize_author())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment