Menu
Coddy logo textTech

Recap - Create a Book Struct

Part of the Logic & Flow section of Coddy's Rust journey — lesson 26 of 66.

challenge icon

Challenge

Easy

You will receive four inputs: a book title, an author name, a publication year (as an integer), and a number of pages (as an integer). Define a Book struct with four fields: title of type String, author of type String, year of type i32, and pages of type i32. Create an instance of this struct using the input values and print the book information.

Requirements:

  • Define a Book struct with fields: title: String, author: String, year: i32, and pages: i32
  • Read the first input as the book title
  • Read the second input as the author name
  • Read the third input and convert it to i32 for the publication year
  • Read the fourth input and convert it to i32 for the number of pages
  • Create an instance of the Book struct with these values
  • Print the book information in the exact format shown below

Input:

  • First line: Book title (e.g., The Rust Programming Language)
  • Second line: Author name (e.g., Steve Klabnik)
  • Third line: Publication year as an integer (e.g., 2018)
  • Fourth line: Number of pages as an integer (e.g., 552)

Output:

  • First line: Book: [title]
  • Second line: Author: [author]
  • Third line: Year: [year]
  • Fourth line: Pages: [pages]

Try it yourself

use std::io;

// TODO: Define the Book struct here with fields: title, author, year, and pages

fn main() {
    // Read book title
    let mut title = String::new();
    io::stdin().read_line(&mut title).expect("Failed to read line");
    let title = title.trim().to_string();
    
    // Read author name
    let mut author = String::new();
    io::stdin().read_line(&mut author).expect("Failed to read line");
    let author = author.trim().to_string();
    
    // Read publication year
    let mut year_input = String::new();
    io::stdin().read_line(&mut year_input).expect("Failed to read line");
    let year: i32 = year_input.trim().parse().expect("Failed to parse year");
    
    // Read number of pages
    let mut pages_input = String::new();
    io::stdin().read_line(&mut pages_input).expect("Failed to read line");
    let pages: i32 = pages_input.trim().parse().expect("Failed to parse pages");
    
    // TODO: Create an instance of the Book struct using the input values
    
    // TODO: Print the book information in the required format
}

All lessons in Logic & Flow