Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

트레이트

trait는 알 수 없는 타입 Self에 대해 정의된 메서드들의 모음입니다. 이들은 동일한 트레이트 내에 선언된 다른 메서드에 접근할 수 있습니다.

트레이트는 모든 데이터 타입에 대해 구현될 수 있습니다. 아래 예제에서는 메서드 그룹인 Animal을 정의합니다. 그런 다음 Animal traitSheep 데이터 타입에 대해 구현하여 Sheep으로 Animal의 메서드를 사용할 수 있게 합니다.

struct Sheep { naked: bool, name: &'static str }

trait Animal {
    // 연관 함수 시그니처; `Self`는 구현하는 타입을 가리킵니다.
    fn new(name: &'static str) -> Self;

    // 메서드 시그니처; 이들은 문자열을 반환할 것입니다.
    fn name(&self) -> &'static str;
    fn noise(&self) -> &'static str;

    // 트레이트는 기본 메서드 정의를 제공할 수 있습니다.
    fn talk(&self) {
        println!("{}가 말하길 {}", self.name(), self.noise());
    }
}

impl Sheep {
    fn is_naked(&self) -> bool {
        self.naked
    }

    fn shear(&mut self) {
        if self.is_naked() {
            // 구현자의 메서드는 구현자의 트레이트 메서드를 사용할 수 있습니다.
            println!("{}는 이미 벌거벗었습니다...", self.name());
        } else {
            println!("{}가 털을 깎습니다!", self.name);

            self.naked = true;
        }
    }
}

// `Sheep`에 대해 `Animal` 트레이트를 구현합니다.
impl Animal for Sheep {
    // `Self`는 구현하는 타입인 `Sheep`입니다.
    fn new(name: &'static str) -> Sheep {
        Sheep { name: name, naked: false }
    }

    fn name(&self) -> &'static str {
        self.name
    }

    fn noise(&self) -> &'static str {
        if self.is_naked() {
            "메에에에?"
        } else {
            "메에에에!"
        }
    }

    // 기본 트레이트 메서드는 재정의(오버라이드)될 수 있습니다.
    fn talk(&self) {
        // 예를 들어, 조용한 사색을 추가할 수 있습니다.
        println!("{}가 잠시 멈춥니다... {}", self.name, self.noise());
    }
}

fn main() {
    // 이 경우에는 타입 어노테이션이 필요합니다.
    let mut dolly: Sheep = Animal::new("돌리");
    // TODO ^ 타입 어노테이션을 제거해 보세요.

    dolly.talk();
    dolly.shear();
    dolly.talk();
}