Archive/Rust

[Rustlings] 15. trait

steelbear 2021. 5. 31. 11:44

trait은 여러 method를 묶어둔 집합이다. 같은 trait을 가진 타입은 trait에서 지정한 method를 사용할 수 있다. 또한 trait을 함수 매개변수의 타입으로 사용하면 해당 trait을 가진 타입 모두 들어갈 수 있다.

trait AppendBar {
  fn append_bar(self) -> Self;
}

impl AppendBar for String {
  fn append_bar(self) -> Self {
    let mut newString = String::new();
    newString.push_str(self.to_str());
    newString.push_str("bar");
    newString
  }
}

impl AppendBar for Vec<String> {
  fn append_bar(self) -> Self {
    let mut newVec = Vec::new();
    newVec.push(self.last().unwrap().to_string);
    newVec.push(String::from("bar"));
    newVec
  }
}