Structs
A struct groups related values together under one named type. Unlike a tuple, every field has a name, which makes the code that creates and uses it self-documenting.
struct Person {
name: String,
age: u32,
}
fn main() {
let alice = Person {
name: String::from("Alice"),
age: 30,
};
println!("{} is {} years old", alice.name, alice.age);
}Alice is 30 years old
Methods with impl
An impl block attaches functions to a struct. A method that takes &self borrows the instance it's called on, reading its fields without taking ownership of it — rect.area() below reads width and height without consuming rect.
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
}
fn main() {
let rect = Rectangle { width: 10, height: 5 };
println!("Area: {}", rect.area());
}Area: 50
Next: enums and pattern matching — representing a value that's one of several distinct variants, and match's guarantee that you've handled every one.
Practice exercise
Define a struct Book with fields title: String and price: f64. Add a method total(&self, quantity: u32) -> f64 that returns self.price * quantity as f64. Create a Book with title "Dune" and price 15.0, then print book.total(3).