요약 - 제네릭 프린터
Coddy Rust 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 61개 중 44번째.
챌린지
쉬움trait bounds의 강력한 기능을 보여 주는 유연한 announcement 시스템을 만들어 봅시다! Printable trait와 이 trait를 Implement하는 any type을 announce할 수 있는 generic function을 만들면서, generics와 traits가 어떻게 함께 작동하여 재사용 가능하고 type-safe한 code를 만드는지 알아봅니다.
code를 두 개의 파일로 구성합니다:
printable.rs: publicPrintabletrait를 Define하고,&self를 takes하여String을 returns하는print_infomethod를 정의합니다. 그런 다음Printable을 Implement하는 any typeT를 받는announce라는 public generic function을 만듭니다. 이 function은 item에서print_info()를 호출한 result인{info}를 사용하여Announcement: {info}를 print해야 합니다.main.rs:Printable을 Implement하는 두 개의 public struct를 Create합니다:Person: publicnamefield(String)을 가집니다. 이 struct의print_info는Person: {name}을 returns해야 합니다.Product: publicname(String) 및price(f64) fields를 가집니다. 이 struct의print_info는Product: {name} - ${price}를 returns해야 합니다.
announce를 호출하여 generic function이 anyPrintabletype과 함께 작동한다는 것을 보여 줍니다.
이 design의 장점은 announce가 Person, Product 또는 앞으로 추가될 any type을 받는지 신경 쓰지 않는다는 것입니다. type이 print_info()를 통해 정보를 제공할 수 있기만 하면 됩니다. trait bound는 이를 compile time에 보장합니다.
출력에는 두 announcement가 모두 표시되어야 합니다:
Announcement: Person: {name}
Announcement: Product: {product_name} - ${price}예를 들어 inputs가 Alice, Laptop, 999.99인 경우:
Announcement: Person: Alice
Announcement: Product: Laptop - $999.99세 개의 inputs를 받습니다: person의 name, product의 name, 그리고 product의 price(f64로 parse).
직접 해보기
mod printable;
use printable::{Printable, announce};
// TODO: public name 필드(String)를 가진 public struct Person을 정의하세요
// Person에 대해 Printable 트레이트를 구현하세요
// print_info는 "Person: {name}"을 반환해야 합니다
// TODO: public name(String)과 price(f64) 필드를 가진 public struct Product를 정의하세요
// Product에 대해 Printable 트레이트를 구현하세요
// print_info는 "Product: {name} - ${price}"를 반환해야 합니다
fn main() {
// 입력을 읽습니다
let mut person_name = String::new();
std::io::stdin().read_line(&mut person_name).expect("Failed to read line");
let person_name = person_name.trim().to_string();
let mut product_name = String::new();
std::io::stdin().read_line(&mut product_name).expect("Failed to read line");
let product_name = product_name.trim().to_string();
let mut price_input = String::new();
std::io::stdin().read_line(&mut price_input).expect("Failed to read line");
let price: f64 = price_input.trim().parse().expect("Failed to parse price");
// TODO: person_name으로 Person 인스턴스를 생성하세요
// TODO: product_name과 price로 Product 인스턴스를 생성하세요
// TODO: Person으로 announce를 호출하세요
// TODO: Product로 announce를 호출하세요
}
객체 지향 프로그래밍의 모든 레슨
직접 연습해 보세요: 온라인 Rust 컴파일러