#anyone can help me with traits

4 messages · Page 1 of 1 (latest)

agile patrol
#

i'm very confusing about traits because in the rust book we started the chapter with the concept of "write less code/stop duplicating your code", in traits it seems to me like we are just writing a duplicated function ```rust
pub trait Summary {
fn summarize(&self) -> String;
}
pub struct NewsArticle {
pub headline: String,
pub location: String,
pub author: String,
pub content: String,
}

impl Summary for NewsArticle {
fn summarize(&self) -> String {
format!("{}, by {} ({})", self.headline, self.author, self.location)
}
}

pub struct Tweet {
pub username: String,
pub content: String,
pub reply: bool,
pub retweet: bool,
}

impl Summary for Tweet {
fn summarize(&self) -> String {
format!("{}: {}", self.username, self.content)
}
}

(i have a background in python).
wary oar
#

You only need to define and implement a trait is if you are also going to write a function that is generic over that trait — that can take either NewsArticle or Tweet or any other type implementing Summary.
If you are not going to write such a function, then the trait is unnecessary.

agile patrol
wary oar
#

The book will get to that later, starting with the section “Traits as Parameters”.