Structs and Methods
Model real-world data with structs and attach behavior with methods.
Learning objectives
- Define a struct
- Create struct instances
- Implement methods with impl
Structs
A struct groups related data into one custom type. It is useful for representing objects such as students, products, accounts, or game characters.
Creating Instances
You create a struct instance by providing values for its fields.
Methods
Methods are functions associated with a struct. They are defined inside an impl block.
Example code
struct Book {
title: String,
pages: u32,
}
impl Book {
fn summary(&self) {
println!("{} has {} pages.", self.title, self.pages);
}
}
fn main() {
let book = Book {
title: String::from("Rust Made Easy"),
pages: 300,
};
book.summary();
}
Practice task: Create a Student struct with name and mark fields, then add a method that prints the student profile.