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

슈퍼트레이트

Rust에는 “상속“이 없지만, 한 트레이트를 다른 트레이트의 슈퍼셋(superset)으로 정의할 수 있습니다. 예를 들어:

trait Person {
    fn name(&self) -> String;
}

// Person은 Student의 슈퍼트레이트입니다.
// Student를 구현하려면 Person도 구현해야 합니다.
trait Student: Person {
    fn university(&self) -> String;
}

trait Programmer {
    fn fav_language(&self) -> String;
}

// CompSciStudent(컴퓨터 공학 학생)는 Programmer와 Student 모두의 서브트레이트입니다.
// CompSciStudent를 구현하려면 두 슈퍼트레이트를 모두 구현해야 합니다.
trait CompSciStudent: Programmer + Student {
    fn git_username(&self) -> String;
}

fn comp_sci_student_greeting(student: &dyn CompSciStudent) -> String {
    format!(
        "제 이름은 {}이고 {}에 다닙니다. 제가 가장 좋아하는 언어는 {}입니다. 제 Git 사용자 이름은 {}입니다.",
        student.name(),
        student.university(),
        student.fav_language(),
        student.git_username()
    )
}

struct CSStudent {
    name: String,
    university: String,
    fav_language: String,
    git_username: String
}

impl Programmer for CSStudent {
    fn fav_language(&self) -> String {
        self.fav_language.clone()
    }
}

impl Student for CSStudent {
    fn university(&self) -> String {
        self.university.clone()
    }
}

impl Person for CSStudent {
    fn name(&self) -> String {
        self.name.clone()
    }
}

impl CompSciStudent for CSStudent {
    fn git_username(&self) -> String {
        self.git_username.clone()
    }
}

fn main() {
    let student = CSStudent {
        name: String::from("앨리스"),
        university: String::from("MIT"),
        fav_language: String::from("러스트"),
        git_username: String::from("alice_codes"),
    };

    let greeting = comp_sci_student_greeting(&student);
    println!("{}", greeting);
}

참고:

러스트 프로그래밍 언어의 슈퍼트레이트 장