Pybites Logo Rust Platform

Basic Struct

Level: intro (score: 1)

In Python 🐍, you’d use a class or dataclass (or named tuple) to group related fields. In Rust 🦀, you use a struct.

Structs let you define your own types by grouping fields together — and they’re a core building block of Rust programs.


Your task:

Define a struct Book with the following fields:

  • title: String
  • author: String
  • pages: u32

Then use impl to add this method to it:

pub fn describe_book(&self) -> String {
    // ...
}

Which returns a string like:

"The book 'The Hobbit' by J.R.R. Tolkien has 310 pages."


🔍 Note on &self
Methods inside an impl block usually take &self, which is a borrowed reference to the instance (think self in Python but with Rust's ownership model on top of it).
This lets you call the method like book.describe() without taking ownership.


This exercise introduces:

  • Defining a struct
  • Field access via dot syntax
  • String formatting
  • Impl blocks for struct methods (revisiting borrowing rules)

🧠 Structs are the foundation for more complex Rust programs. Master them early!


✅ Example test

let book = Book {
    title: String::from("The Hobbit"),
    author: String::from("J.R.R. Tolkien"),
    pages: 310,
};

assert_eq!(book.describe_book(), "The book 'The Hobbit' by J.R.R. Tolkien has 310 pages.");