Rust
[Rust] 트레잇(Trait)
dev_dean
2022. 5. 8. 14:13
타입들이 공통적으로 갖는 동작에 대하여 추상화하도록 해주는 도구인 트레잇에 대해 알아보겠습니다.
트레잇(Trait)은 다른 언어들에서 인터페이스라고 부르는 기능과 유사합니다.
pub trait Summarizable {
fn summary(&self) -> String;
}
트레잇의 선언은 위와 같이 가능합니다. trait 다음 이름이 오고 메소드의 선언을 적어줍니다.
선언된 트레잇은 다음과 같이 구현될 수 있습니다.
pub struct NewsArticle {
pub headline: String,
pub location: String,
pub author: String,
pub content: String,
}
impl Summarizable for NewsArticle {
fn summary(&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 Summarizable for Tweet {
fn summary(&self) -> String {
format!("{}: {}", self.username, self.content)
}
}
2개의 서로 다른 구조체가 모두 Summarizable 트레잇을 구현하고 있습니다. 하지만 구현하는 메소드의 내용은 서로 다른 것을 알 수 있습니다.
트레잇을 구현했다면 호출은 일반 메소드의 호출과 같은 방법으로 할 수 있습니다.
tweet.summary();
또한 트레잇의 메소드를 직접 구현하지 않고 기본 로직을 구현한 다음 하위 구조체에서 오버라이드를 할지 기본 구현된 내용을 사용할지 선택할 수 있습니다.
pub trait Summarizable {
fn author_summary(&self) -> String;
fn summary(&self) -> String {
format!("(Read more from {}...)", self.author_summary())
}
}
impl Summarizable for Tweet {
fn author_summary(&self) -> String {
format!("@{}", self.username)
}
}
위를 보면 author_summary만을 Tweet이 구현했는데 summary를 구현하지 않았지만 trait의 선언에서 summary의 몸통이 구현되어 있기 때문에 tweet.summary()를 호출할 수 있습니다.