도형 넓이 계산기
Coddy Rust 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 61개 중 61번째.
챌린지
쉬움이 최종 challenge에서는 trait, trait object, polymorphism을 함께 사용하여 하나의 collection에 저장된 서로 다른 shape의 전체 area를 계산하는 실용적인 문제를 해결합니다.
trait object와 polymorphism의 강력한 기능을 보여 주는 shape area 계산기를 만들어 봅시다! 서로 다른 shape인 원과 정사각형을 하나의 collection에 함께 저장하고 통합된 interface를 통해 전체 area를 계산하는 system을 만들게 됩니다.
code를 세 개의 file에 나누어 구성합니다:
shape.rs:areamethod를 가진Shapetrait을 Define합니다. 이 trait은 모든 shape이 충족해야 하는 contract을 설정합니다.shapes.rs: trait을 Implement하는 두 개의 struct를 Create합니다.Circle에는radius(f64)가 있고,Square에는side(f64)가 있습니다. 각 struct는 적절한 area formula를 사용하여Shapetrait을 Implement해야 합니다. 원에는 π로3.14159를 사용합니다.main.rs: 두 module을 모두 가져오고Vec<Box<dyn Shape>>을 받아 모든 area의 합을 returns하는total_areafunction을 Create합니다. 제공된 input을 사용하여 원과 정사각형을 Create하고, 이를 trait object의 vector에 Store한 다음, 전체 area를 계산하고 result를 print합니다.
area formula은 다음과 같습니다:
- Circle:
3.14159 × radius × radius - Square:
side × side
output에는 모든 shape의 전체 area가 표시되어야 합니다:
Total area: {total}예를 들어 input이 2.0(원 radius) 및 3.0(정사각형 side)인 경우:
Total area: 21.56636이는 다음과 같기 때문입니다: Circle area = 3.14159 × 2² = 12.56636, Square area = 3² = 9, Total = 21.56636
그리고 input이 1.0 및 4.0인 경우:
Total area: 19.14159두 개의 input을 받습니다. 원의 radius와 정사각형의 side length를 각각 f64로 parse합니다.
직접 해보기
mod shape;
mod shapes;
use shape::Shape;
use shapes::{Circle, Square};
// TODO: total_area 함수를 구현하세요
// Vec<Box<dyn Shape>>를 받아 모든 넓이의 합을 f64로 반환해야 합니다
fn total_area(shapes: Vec<Box<dyn Shape>>) -> f64 {
// TODO: 모든 도형의 넓이 합을 계산하여 반환하세요
0.0
}
fn main() {
let mut input1 = String::new();
std::io::stdin().read_line(&mut input1).expect("Failed to read line");
let radius: f64 = input1.trim().parse().expect("Invalid number");
let mut input2 = String::new();
std::io::stdin().read_line(&mut input2).expect("Failed to read line");
let side: f64 = input2.trim().parse().expect("Invalid number");
// TODO: 주어진 반지름으로 Circle을 생성하세요
// TODO: 주어진 변의 길이로 Square를 생성하세요
// TODO: 두 도형을 Vec<Box<dyn Shape>>에 저장하세요
// TODO: total_area를 호출하고 결과를 "Total area: {total}" 형식으로 출력하세요
}
객체 지향 프로그래밍의 모든 레슨
직접 연습해 보세요: 온라인 Rust 컴파일러