[Rust] 10장 트레이트

1. 트레이트 정의하기 

트레이트는 특정 행동을 정의하고, 이를 구현하는 타입에 적용하는 방식으로, 트레이트를 정의하기 위해  trait 키워드를 사용합니다. 예를 들어 Speak라는 트레이트를 정의할 수 있습니다.

trait Speak {
    fn speak(&self);
}

2. 트레이트 구현하기

구현하고자 하는 타입에 대해 트레이트를 구현합니다. 

trait Speak {
    fn speak(&self);
}

struct Running;

impl Speak for Running {
    fn speak(&self) {
        println!("Run!");
    } 
}

3. 트레이트 객체 사용하기 

트레이트 객체를 사용하면 다형성을 구현할 수 있습니다. let_speak  함수가 Speak 트레이트를 구현하는 타입을 받을 수 있습니다.

trait Speak {
    fn speak(&self);
}

struct Running;

impl Speak for Running {
    fn speak(&self) {
        println!("Run!");
    } 
}

fn let_speak(s: &dyn Speak) {
    s.speak();
}

fn main() {
    let run = Running;
    let_speak(&run);
}

4. 트레이트 상속하기 

트레이트를 다른 트레이트에 상속받을 수 있습니다. 이를 통해서 기능을 확장시킬 수 있습니다.

trait Speak {
    fn speak(&self);
}

struct Human;


impl Speak for Human {
    fn speak(&self) {
        println!("Running!");
    }
}

5. 제네릭과 트레이트 사용하기

제네릭 타입에 트레이트 바운드를 사용하여 특정 트레이트를 구현한 타입만을 허용할 수 있습니다.

fn human_speak<T: Speak>(human: T) {
    human.speak();
} 

fn main() {
    let human = Human;
    human_speak(human); // "Running!" 출력
}

6. 기본 메서드 구현하기

트레이트 내에서 기본 메서드를 구현하여, 이를 선택적으로 오버라이드할 수 있습니다.

trait Speak {
    fn speak(&self) {
        println!("Some sound");
    }
}

struct Bird;

impl Speak for Bird {
    fn speak(&self) {
        println!("Tweet!");
    }
}

 
fn main() {
    let bird = Bird;
    bird.speak();
}

7. 연관 타입 사용하기

트레이트 내에서 연관 타입을 정의함으로써, 트레이트를 구현할 때 구체적인 타입을 지정할 수 있습니다.

trait Container {
    type Item;

    fn get(&self) -> Self::Item;
}

struct MyContainer;

impl Container for MyContainer {
    type Item = i32;

    fn get(&self) -> Self::Item {
        42
    }
}

fn main() {
    let container = MyContainer;

    // get 메서드 호출 
    let value: i32 = container.get(); // 연관 타입으로 i32 반환
    println!("Value: {}", value); // "Value: 42" 
}

 

 

GitHub - Koras02/rust-tutorial: https://thinky.tistory.com/category/Back-End/Rust

https://thinky.tistory.com/category/Back-End/Rust. Contribute to Koras02/rust-tutorial development by creating an account on GitHub.

github.com

 

LIST

'Back-End > Rust' 카테고리의 다른 글

[Rust] 11장 고차 함수  (0) 2025.04.04
[Rust] 9장 동시성  (0) 2025.03.20
[Rust] 8장 제네릭  (0) 2025.03.12
[Rust] 7장 모듈  (0) 2025.03.10
[Rust] 6장 에러 처리  (0) 2025.03.08