Basic Structs
Easy
+2 pts
Intro to Rust
12/15
🎯 In Python, you'd use a class or dataclass to group related data:
from dataclasses import dataclass
@dataclass
class City:
name: str
country: str
population: int
def summary(self) -> str:
return f"{self.name} ({self.country}) — population: {self.population}"
Rust's equivalent is a struct with an impl block for methods:
struct City {
name: String,
country: String,
population: u64,
}
impl City {
fn summary(&self) -> String {
format!(
"{} ({}) — population: {}",
self.name, self.country, self.population
)
}
}
Key differences from Python:
- Data and methods are separate. The
structdefines fields. Theimplblock defines methods. In Python, both live inside theclass. &selfis explicit. Python'sselfis always a reference. Rust makes you write&self(borrow) vsself(consume) — you choose whether the method keeps the struct alive.- Fields are private by default. Rust uses
pubto opt-in to visibility (covered in a later exercise). Python uses_underscoreconventions.
Creating struct instances
Rust doesn't have constructors like Python's __init__. You create instances directly:
let city = City {
name: String::from("Tokyo"),
country: String::from("Japan"),
population: 14_000_000,
};
Or you can define a new function by convention (not a language feature):
impl City {
fn new(name: &str, country: &str, population: u64) -> Self {
City {
name: name.to_string(),
country: country.to_string(),
population, // shorthand when field name matches variable name
}
}
}
Your Task
- Define a
Bookstruct with fields:title: String,author: String,pages: u32 - Implement a
describe(&self) -> Stringmethod that returns:"The book '{title}' by {author} has {pages} pages."
Example
let book = Book {
title: String::from("The Hobbit"),
author: String::from("J.R.R. Tolkien"),
pages: 310,
};
assert_eq!(
book.describe(),
"The book 'The Hobbit' by J.R.R. Tolkien has 310 pages."
);
Dive deeper: In our Rust Developer Cohort, you'll refactor free functions into
TokenizerandJsonParserstructs — encapsulating state with methods likeadvance(),peek(), andparse_value().
Further Reading
- The Rust Book — Defining and Instantiating Structs — struct syntax
- The Rust Book — Method Syntax — impl blocks and &self
// Define the Book struct here
// Implement a describe method in an impl block
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_describe_book() {
let book = Book {
title: "The Hobbit".to_string(),
author: "J.R.R. Tolkien".to_string(),
pages: 310,
};
assert_eq!(
book.describe(),
"The book 'The Hobbit' by J.R.R. Tolkien has 310 pages."
);
}
#[test]
fn test_describe_war_and_peace() {
let book = Book {
title: "War and Peace".to_string(),
author: "Leo Tolstoy".to_string(),
pages: 1225,
};
assert_eq!(
book.describe(),
"The book 'War and Peace' by Leo Tolstoy has 1225 pages."
);
}
}