Menu
Coddy logo textTech

도서관 카탈로그

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

challenge icon

챌린지

쉬움

트레이트가 서로 다른 타입을 공통 인터페이스 아래 통합하는 방식을 보여 주는 library catalog 시스템을 만들어 봅시다! 서로 다른 속성을 가진 book과 magazine이 공유 트레이트를 통해 자신을 설명할 수 있는 catalog을 만들게 됩니다.

코드를 세 개의 파일로 구성합니다:

  • catalog.rs: 단일 메서드 description를 가진 CatalogItem 트레이트를 Define합니다. 이 트레이트는 모든 library item이 충족해야 하는 계약을 설정합니다.
  • items.rs: 트레이트를 Implement하는 두 개의 구조체를 Create합니다. Booktitleauthor (both Strings)를 has 있으며, Magazinename (String)과 issue number (u32)를 has 있습니다. 각 구조체는 고유한 description format으로 CatalogItem을 Implement해야 합니다.
  • main.rs: 두 모듈을 가져오고 제공된 inputs를 사용하여 Book과 Magazine의 인스턴스를 Create합니다. 각 item에서 description method를 Call하고 results를 print합니다.

Book description은 다음 format을 따라야 합니다:

Book: {title} by {author}

Magazine description은 다음 format을 따라야 합니다:

Magazine: {name}, Issue {issue}

예를 들어 inputs가 1984, George Orwell, Nature, 42인 경우:

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

그리고 inputs가 The Rust Book, Steve Klabnik, Science Weekly, 156인 경우:

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

네 개의 inputs를 받습니다: book title, book author, magazine name, magazine issue number (마지막 항목은 u32로 parse).

REQUIRED OUTPUT FORMAT: [Your translated content here]

직접 해보기

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: Create a Magazine instance using magazine_name and magazine_issue

    // TODO: 각 항목에 description()을 호출하고 결과 출력
}

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

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