본문 바로가기
Rust

[Rust] Derive 예제 (54일차)

by 꾸압 2023. 2. 7.

 

<예제 코드_1>

// 'Centimeters', a tuple struct that can be compared
#[derive(PartialEq, PartialOrd)]
struct Centimeters(f64);

// 'Inches', a tuple struct that can be printed
#[derive(Debug)]
struct Inches(i32);

impl Inches {
    fn to_centimeters(&self) -> Centimeters {
        let &Inches(inches) = self;

        Centimeters(inches as f64 * 2.54)
    }
}

// 'Seconds', a tuple struct with no additional attributes
struct Seconds(i32);

fn main() {
    let _one_second = Seconds(1);

    // Error: 'Seconds' can't be printed if doesn't implement the 'Debug' trait
    // println!("One second looks like: {:?}", _one_second);
    // TODO & Try uncommenting this line

    let foot = Inches(40);

    println!("One foot equals {:?}", foot);

    let meter = Centimeters(100.0);

    let cmp =
        if foot.to_centimeters() < meter {
            "smaller"
        } else {
            "bigger"
        };
    
    println!("One foot is {} than one meter.", cmp);
}

 


 

<참조 1>

 

 

'Rust' 카테고리의 다른 글

[Rust] 실시간 Chat App in Rocket (56일차)  (0) 2023.02.09
[Rust] Web Crawler 예제 (55일차)  (0) 2023.02.08
[Rust] Tokio 예제 : 기본 (53일차)  (0) 2023.02.05
[Rust] HashMap 예제 (52일차)  (0) 2023.02.03

댓글