Menu
Coddy logo textTech

図書館カタログ

CoddyのRustジャーニー「オブジェクト指向プログラミング」セクションの一部。レッスン 60/61。

challenge icon

チャレンジ

簡単

異なる型を共通のインターフェースの下で統一するトレイトの仕組みを示す、図書館カタログシステムを構築しましょう!プロパティが異なる book と magazine が、共有トレイトを通じてそれぞれの情報を記述できるカタログを作成します。

コードを3つのファイルに分けて整理します。

  • catalog.rs: 1つのメソッド description を持ち、String を返す CatalogItem トレイトを Define します。このトレイトによって、すべての図書館アイテムが満たすべき契約を定めます。
  • items.rs: トレイトを Implement する2つの構造体を作成します。Booktitleauthor(どちらも String)を持ち、Magazinename(String)と issue number(u32)を持ちます。それぞれの構造体は、独自の description format で CatalogItem を Implement します。
  • main.rs: 両方のモジュールを読み込み、提供された inputs を使用して Book と Magazine のインスタンスを作成します。各 item で description method を Call し、results を print します。

Book の description は次の format に従う必要があります。

Book: {title} by {author}

Magazine の description は次の format に従う必要があります。

Magazine: {name}, Issue {issue}

たとえば、inputs が 1984George OrwellNature42 の場合:

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

また、inputs が The Rust BookSteve KlabnikScience Weekly156 の場合:

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

4つの inputs を受け取ります:book title、book author、magazine name、magazine issue number(最後のものは u32 として parse します)。

自分で試してみよう

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オンラインコンパイラ