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

New Type 관용구

newtype 관용구는 프로그램에 올바른 타입의 값이 제공됨을 컴파일 타임에 보장해 줍니다.

For example, a function that measures distance in miles, must be given a value of type Miles.

struct Miles(f64);

struct Kilometers(f64);

impl Miles {
    pub fn to_kilometers(&self) -> Kilometers {
        Kilometers(self.0 * 1.609344)
    }
}

impl Kilometers {
    pub fn to_miles(&self) -> Miles {
        Miles(self.0 / 1.609344)
    }
}

fn is_a_marathon(distance: &Miles) -> bool {
    distance.0 >= 26.2
}

fn main() {
    let distance = Miles(30.0);
    let distance_km = distance.to_kilometers();
    println!("Is a marathon? {}", is_a_marathon(&distance));
    println!("Is a marathon? {}", is_a_marathon(&distance_km.to_miles()));
    // println!("Is a marathon? {}", is_a_marathon(&distance_km));
}

Uncomment the last print statement to observe that the type supplied must be Miles.

newtype의 값을 기본 타입으로 얻으려면, 다음과 같이 튜플 또는 구조 분해 문법을 사용할 수 있습니다:

struct Miles(f64);

fn main() {
    let distance = Miles(42.0);
    let distance_as_primitive_1: f64 = distance.0; // 튜플
    let Miles(distance_as_primitive_2) = distance; // 구조 분해
}

참고:

structs