Menu
Coddy logo textTech

Library Catalog

Part of the Object Oriented Programming section of Coddy's Rust journey — lesson 60 of 61.

challenge icon

Challenge

Easy

Let's build a library catalog system that demonstrates how traits unify different types under a common interface! You'll create a catalog where books and magazines—despite having different properties—can all describe themselves through a shared trait.

You'll organize your code across three files:

  • catalog.rs: Define the CatalogItem trait with a single method description that returns a String. This trait establishes the contract that all library items must fulfill.
  • items.rs: Create two structs that implement your trait. A Book has a title and author (both Strings), while a Magazine has a name (String) and issue number (u32). Each struct should implement CatalogItem with its own unique description format.
  • main.rs: Bring in both modules and create instances of Book and Magazine using the provided inputs. Call the description method on each item and print the results.

Your Book description should follow this format:

Book: {title} by {author}

Your Magazine description should follow this format:

Magazine: {name}, Issue {issue}

For example, with inputs 1984, George Orwell, Nature, and 42:

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

And with inputs The Rust Book, Steve Klabnik, Science Weekly, and 156:

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

You will receive four inputs: book title, book author, magazine name, and magazine issue number (parse the last one as u32).

Try it yourself

mod catalog;
mod items;

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

fn main() {
    // Read inputs
    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: Create a Book instance using book_title and book_author

    // TODO: Create a Magazine instance using magazine_name and magazine_issue

    // TODO: Call description() on each item and print the results
}

All lessons in Object Oriented Programming