Archive/Rust

[Rustlings] 15. trait

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
  }
}

'Archive > Rust' 카테고리의 다른 글

[Rustlings] 17. Standard Library Types  (0) 2021.06.04
[Rustlings] 16. Testing  (0) 2021.06.01
[Rustlings] 14. Result  (0) 2021.05.30
[Rustlings] 13. Option  (0) 2021.05.30
[Rustlings] 12. Generic  (0) 2021.05.29