본문 바로가기
Rust

[Rust] Trait 예제 (24일차)

by 꾸압 2023. 1. 6.

 

<예제 코드_1>

use std::cmp::PartialOrd;

fn largest<T: PartialOrd + Copy>(list: &[T]) -> T {
    let mut largest = list[0];

    for &item in list.iter() {
        if item > largest {
            largest = item;
        }
    }

    largest
}

fn main() {
    let numbers = vec![34, 50, 25, 100, 65];

    let result = largest(&numbers);
    println!("The largest number is {}", result);

    let chars = vec!['y', 'm', 'a', 'q'];

    let result = largest(&chars);
    println!("The largest char is {}", result);
}

 


 

<예제 코드_2>

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

trait Animal {
    // Associated function signature;   'self' refers to the implementor type.
    fn new(name: &'static str) -> Self;

    // Method signatures; these will return a string.
    fn name(&self) -> &'static str;
    fn noise(&self) -> &'static str;

    // Traits can provide default method definitions.
    fn talk(&self) {
        println!("{} says {}", self.name(), self.noise());
    }
}

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

    fn shear(&mut self) {
        if self.is_naked() {
            // Implemetor methods ca use the implementor's trait mehods.
            println!("{} is already naked...", self.name());
        } else {
            println!("{} gets a haircut!", self.name);

            self.naked = true;
        }
    }
}

// Implement the 'Animal' trait for 'Sheep'.
impl Animal for Sheep {
    // 'Self' is the implementor type: '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() {
            "baaaah?"
        } else {
            "baaaah!"
        }
    }

    // Default trait methods can be overridden
    fn talk(&self) {
        // For example, we can add some quiet contemplation.
        println!("{} pauses briefly... {}", self.name, self.noise());
    }
}

fn main() {
    // Type annotation is necessary in this case.
    let mut dolly: Sheep = Animal::new("Dolly");
    // TODO ^ Try removing the type annotationsd.

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

 


 

<참조 1> https://rinthel.github.io/rust-lang-book-ko/ch10-02-traits.html

<참조 2> https://doc.rust-lang.org/rust-by-example/trait.html

 

 

'Rust' 카테고리의 다른 글

[Rust] Testing 예제 (26일차)  (0) 2023.01.08
[Rust] Lifetime 예제 (25일차)  (0) 2023.01.07
[Rust] Generic : Data Type 예제 (23일차)  (0) 2023.01.05
[Rust] Generic 예제 (22일차)  (0) 2023.01.04

댓글