Structs, Enums, and Matching
Structs
Grouping Fields with Methods
A struct groups named fields. An impl block adds methods that read the fields through &self.
Program
Play the program to build a rectangle and compute its area.
structs.rs
Replay: real traced execution (multi-file project)
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
}
fn main() {
let rect = Rectangle { width: 4, height: 3 };
let area = rect.area();
println!("{area}");
}
rect ← (empty)
12fn main() {13 let rec→ (empty)t = Rectangle { width: 4, height: 3 };14 let area = rect.area();15 println!("{area}");area ← 12
13 let rect = Rectangle { width: 4, height: 3 };14 let are→ 12a = rect.area();15 println!("{area}");16}output12
Follow the Trace
rectisRectangle { width: 4, height: 3 }.- The program calls
rect.area(). - Inside the method,
self.widthis4. self.heightis3.- The return value is
12, and the program prints12. | trace point | value | | --- | --- | |rect.width| 4 | |rect.height| 3 | | method call |rect.area()| | returned area | 12 | | stdout |12|
struct
`struct Rectangle` groups related fields.
impl
`impl Rectangle` attaches methods to the type.
&self
`area(&self)` borrows the instance to read its fields.
Exercise: structs.rs
Reproduce the output 12, then trace which two fields the area method multiplies.