100 Exercises To Learn Rust - 5.4 if let 풀기

목차

풀이

enum Shape {
    Circle { radius: f64 },
    Square { border: f64 },
    Rectangle { width: f64, height: f64 },
}

impl Shape {
    // TODO: Implement the `radius` method using
    //  either an `if let` or a `let/else`.
    pub fn radius(&self) -> f64 {
        if let Shape::Circle { radius } =  self {
            *radius
        }
            else  {
                panic!();
            }
    }
}

 

Shape::Circle {radius}인 경우에만 radius를 반환해야 한다. 다른 경우에는 패닉이 발생하도록 한다.