Menu
Coddy logo textTech

도서관 카탈로그

Coddy Rust 여정의 Object Oriented Programming 섹션에 포함된 레슨 — 61개 중 60번째.

challenge icon

챌린지

쉬움

트레이트(trait)가 어떻게 서로 다른 타입들을 공통 인터페이스 아래로 통합하는지 보여주는 도서관 카탈로그 시스템을 만들어 봅시다! 서로 다른 속성을 가진 도서(Book)와 잡지(Magazine)가 공유된 트레이트를 통해 각자 자신을 설명할 수 있는 카탈로그를 만들게 됩니다.

코드는 세 개의 파일로 구성됩니다:

  • catalog.rs: String을 반환하는 단일 메서드 description을 가진 CatalogItem 트레이트를 정의합니다. 이 트레이트는 모든 도서관 항목이 충족해야 하는 계약을 설정합니다.
  • items.rs: 트레이트를 구현하는 두 개의 구조체를 만듭니다. Booktitleauthor(둘 다 String)를 가지며, Magazinename(String)과 issue 번호(u32)를 가집니다. 각 구조체는 고유한 설명 형식을 사용하여 CatalogItem을 구현해야 합니다.
  • main.rs: 두 모듈을 가져와서 제공된 입력을 사용하여 Book과 Magazine의 인스턴스를 생성합니다. 각 항목에 대해 description 메서드를 호출하고 결과를 출력합니다.

Book 설명은 다음 형식을 따라야 합니다:

Book: {title} by {author}

Magazine 설명은 다음 형식을 따라야 합니다:

Magazine: {name}, Issue {issue}

예를 들어, 입력값이 1984, George Orwell, Nature, 42인 경우:

Book: 1984 by George Orwell
Magazine: Nature, Issue 42

그리고 입력값이 The Rust Book, Steve Klabnik, Science Weekly, 156인 경우:

Book: The Rust Book by Steve Klabnik
Magazine: Science Weekly, Issue 156

네 개의 입력을 받게 됩니다: 도서 제목, 도서 저자, 잡지 이름, 잡지 호수(마지막 값은 u32로 파싱하세요).

직접 해보기

mod catalog;
mod items;

use catalog::CatalogItem;
use items::{Book, Magazine};

fn main() {
    // 입력 읽기
    let mut book_title = String::new();
    std::io::stdin().read_line(&mut book_title).expect("Failed to read line");
    let book_title = book_title.trim().to_string();

    let mut book_author = String::new();
    std::io::stdin().read_line(&mut book_author).expect("Failed to read line");
    let book_author = book_author.trim().to_string();

    let mut magazine_name = String::new();
    std::io::stdin().read_line(&mut magazine_name).expect("Failed to read line");
    let magazine_name = magazine_name.trim().to_string();

    let mut issue_input = String::new();
    std::io::stdin().read_line(&mut issue_input).expect("Failed to read line");
    let magazine_issue: u32 = issue_input.trim().parse().expect("Failed to parse issue number");

    // TODO: book_title과 book_author를 사용하여 Book 인스턴스 생성

    // TODO: magazine_name과 magazine_issue를 사용하여 Magazine 인스턴스 생성

    // TODO: 각 아이템에 대해 description()을 호출하고 결과 출력
}

Object Oriented Programming의 모든 레슨