Menu
Coddy logo textTech

요약 - Shape Enum

Coddy Rust 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 61개 중 18번째.

challenge icon

챌린지

쉬움

각 도형이 자체 치수를 저장하도록 enum을 사용해 다양한 도형을 나타내는 기하 계산기를 만들어 봅시다. Shape enum은 single type이 서로 다른 데이터 구조를 보유하고 메서드를 통해 통합된 동작을 제공하는 방법을 보여 줍니다.

코드를 구성하기 위해 두 개의 파일을 만듭니다:

  • shape.rs: 두 variant를 가진 public Shape enum을 Define합니다:
    • Circle: 반지름을 나타내는 single f64를 holds합니다(tuple syntax).
    • Rectangle: named fields를 holds합니다: width (f64) 및 height (f64)
    variant에 따라 appropriate한 넓이를 calculate하기 위해 pattern matching을 using하는 area method를 Implement합니다. 원의 경우 π로 3.14159를 사용합니다.
  • main.rs: shape 모듈을 가져오고, 제공된 inputs를 using하여 각 shape variant의 one instance를 만들고, 각 shape의 넓이를 Print합니다.

area method는 f64를 반환해야 합니다. matching할 때 각 variant를 destructure하여 치수를 추출하고 appropriate한 공식을 적용합니다:

  • Circle 넓이: π × radius²
  • Rectangle 넓이: width × height

출력은 각 shape의 넓이를 한 줄에 하나씩, 정확히 소수점 한 자리로 표시해야 합니다:

Circle area: {area}
Rectangle area: {area}

예를 들어 Circle의 radius가 5.0이고 width가 4.0, height가 6.0인 Rectangle의 경우 출력은 다음과 같습니다:

Circle area: 78.5
Rectangle area: 24.0

세 개의 inputs를 받게 됩니다: Circle의 radius, Rectangle의 width, Rectangle의 height입니다.

직접 해보기

mod shape;

use shape::Shape;

fn main() {
    // 입력 읽기
    let mut radius_input = String::new();
    std::io::stdin().read_line(&mut radius_input).expect("Failed to read line");
    let radius: f64 = radius_input.trim().parse().expect("Invalid number");

    let mut width_input = String::new();
    std::io::stdin().read_line(&mut width_input).expect("Failed to read line");
    let width: f64 = width_input.trim().parse().expect("Invalid number");

    let mut height_input = String::new();
    std::io::stdin().read_line(&mut height_input).expect("Failed to read line");
    let height: f64 = height_input.trim().parse().expect("Invalid number");

    // TODO: radius를 사용하여 Circle 도형 생성
    
    // TODO: width와 height를 사용하여 Rectangle 도형 생성
    
    // TODO: 각 도형의 면적을 소수점 한 자리로 출력
    // Format: "Circle area: {area}" and "Rectangle area: {area}"
}

객체 지향 프로그래밍의 모든 레슨

직접 연습해 보세요: 온라인 Rust 컴파일러