Modeling Data · 12 min · free with an account

Structs

Lesson preview · about 30%

Structs give related data names and a stable shape.

Core idea

self consumes, &self reads, &mut self modifies.

Start with the idea

impl blocks attach constructors and methods to the type. The receiver spells out the ownership contract: self consumes the value, &self borrows it for reading, and &mut self borrows it for modification — so a method signature tells you what it will do before you read the body.

A struct groups values that belong to one concept. Rectangle { width, height } gives those numbers names, so the caller cannot silently confuse the two positions in a tuple. Choose field types that express the valid domain; unsigned dimensions reject negative values at the type level, though you still need to think about multiplication overflow for very large inputs. Construct one value, print its area, then change only its width to see how the named fields clarify the operation.

An impl block puts operations next to the type they describe. An associated function such as Rectangle::new(width, height) has no self receiver and can validate input during construction. A method such as area(&self) borrows an existing rectangle.

Keep learning, for free

The rest of this lesson is waiting for you.

Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.

No payment details. Your account opens the complete Academy.

← All lessons in Rust Basics