Structs
Part 1 · Rust. Group related data into your own types with structs, then give them behaviour with impl blocks, methods, and a new() constructor.
So far we’ve stored the café’s data in loose variables: a name here, a price there. That’s fine for one muffin, but the Rusty Bean Café has a whole menu. Real programs group related pieces of data into one named thing. In Rust, that thing is a struct.
What is a struct?
A struct (short for “structure”) is a custom type you design yourself. It bundles several named values, called fields, into one unit.
Think of a struct as a blank form. A “menu item” form has boxes for the name, the price, and whether it’s available. The form design is the struct. Each filled-in copy of the form is an instance.
Defining a struct
struct MenuItem { name: String, price_cents: u32, available: bool,}
fn main() { let latte = MenuItem { name: String::from("Latte"), price_cents: 450, available: true, };
println!("{} costs {} cents", latte.name, latte.price_cents); println!("Available today? {}", latte.available);}Latte costs 450 centsAvailable today? trueStep by step:
struct MenuItem { ... }defines the form. Struct names useUpperCamelCase.- Each field has a name and a type, like
price_cents: u32. We store money as whole cents in au32, which avoids rounding errors. - In
main, we create an instance by filling in every field. - We read a field with a dot:
latte.name.
Note
The struct owns its fields. When latte goes out of scope, its name String is dropped with it. Everything from the Ownership lesson still applies.
Changing fields
To change a field, the whole instance must be mutable:
struct MenuItem { name: String, price_cents: u32, available: bool,}
fn main() { let mut muffin = MenuItem { name: String::from("Blueberry Muffin"), price_cents: 300, available: true, };
muffin.available = false; // sold out! muffin.price_cents = 150; // half price at closing time println!("{} available? {}", muffin.name, muffin.available); println!("Now {} cents", muffin.price_cents);}Blueberry Muffin available? falseNow 150 centsRust doesn’t let you mark only some fields as mut. It’s all or nothing, with let mut on the instance.
Field init shorthand
When a variable has the same name as a field, you can skip repeating it:
let name = String::from("Espresso");let price_cents = 300;
let espresso = MenuItem { name, price_cents, available: true };name here means name: name. It’s a small thing, but you’ll see it everywhere.
Printing a whole struct with #[derive(Debug)]
What if you try println!("{latte}")? Rust doesn’t know how you want a MenuItem displayed, so it refuses. For quick debugging, you can ask Rust to generate a developer-friendly printout:
#[derive(Debug)]struct MenuItem { name: String, price_cents: u32, available: bool,}
fn main() { let latte = MenuItem { name: String::from("Latte"), price_cents: 450, available: true, };
println!("{latte:?}"); println!("{latte:#?}");}MenuItem { name: "Latte", price_cents: 450, available: true }MenuItem { name: "Latte", price_cents: 450, available: true,}#[derive(Debug)]is an attribute. It tells the compiler “write the debug-printing code for me”.{latte:?}uses the debug format on one line.{latte:#?}is the “pretty” debug format, one field per line.
Note
When you run this, the compiler shows a yellow warning: fields `name`, `price_cents`, and `available` are never read. That’s because printing with {:?} doesn’t count as “using” a field. A warning is only a hint, not an error: the program still compiles and runs. In a real app you’d use those fields elsewhere and the warning would go away. You’ll see this warning in a few small examples on this page, and it’s safe to ignore while learning.
Tip
Add #[derive(Debug)] to almost every struct you write while learning. Being able to print a value is the fastest way to see what’s going on.
Methods with impl
Data is half the story. A menu item can also do things, like format its price. Functions that belong to a type are called methods, and they live in an impl block (short for “implementation”).
struct MenuItem { name: String, price_cents: u32, available: bool,}
impl MenuItem { fn price_label(&self) -> String { format!("${}.{:02}", self.price_cents / 100, self.price_cents % 100) }
fn mark_sold_out(&mut self) { self.available = false; }}
fn main() { let mut scone = MenuItem { name: String::from("Cheese Scone"), price_cents: 375, available: true, };
println!("{}: {}", scone.name, scone.price_label()); scone.mark_sold_out(); println!("Available: {}", scone.available);}Cheese Scone: $3.75Available: falseLet’s walk through it:
impl MenuItem { ... }says “these functions belong toMenuItem”.- The first parameter
&selfmeans “borrow the instance this method was called on, read-only”. It’s shorthand forself: &MenuItem. - Inside,
self.price_centsreads a field of that instance. mark_sold_outtakes&mut selfbecause it changes a field. That’s whysconemust belet mut.- You call methods with a dot:
scone.price_label(). Rust borrowssconefor you automatically.
The choice of self follows the borrowing rules you just learned:
| First parameter | Meaning | Use it when the method… |
|---|---|---|
&self |
borrow read-only | only reads data |
&mut self |
borrow mutably | changes data |
self |
take ownership | consumes the value (rare at first) |
Associated functions and new
Not every function in an impl block needs an instance. Functions without self are called associated functions. The most common one is a constructor called new, a function that builds a fresh instance.
#[derive(Debug)]struct MenuItem { name: String, price_cents: u32, available: bool,}
impl MenuItem { fn new(name: &str, price_cents: u32) -> MenuItem { MenuItem { name: String::from(name), price_cents, available: true, } }}
fn main() { let tea = MenuItem::new("Tea", 250); println!("{tea:?}");}MenuItem { name: "Tea", price_cents: 250, available: true }newhas noself, so it’s an associated function.- You call it with
::on the type, not on an instance:MenuItem::new(...). You’ve already used one:String::from. newtakes a friendly&strand turns it into an ownedString.- It sets a sensible default,
available: true, so callers don’t have to.
Inside an impl block you can also write Self (capital S) instead of repeating the type name. fn new(...) -> Self and Self { ... } mean exactly the same as using MenuItem. You’ll see this style often in real code.
Warning
Don’t mix up the two kinds of call. Methods use a dot on an instance (tea.price_label()). Associated functions use :: on the type (MenuItem::new(...)). Writing MenuItem.new(...) is a compile error.
Structs inside structs
Fields can be any type, even other structs. Here’s an order line:
struct MenuItem { name: String, price_cents: u32,}
struct OrderLine { item: MenuItem, quantity: u32,}
impl OrderLine { fn total_cents(&self) -> u32 { self.item.price_cents * self.quantity }}
fn main() { let line = OrderLine { item: MenuItem { name: String::from("Croissant"), price_cents: 325 }, quantity: 3, }; println!("{} x{} = {} cents", line.item.name, line.quantity, line.total_cents());}Croissant x3 = 975 centsDots chain: self.item.price_cents means “the price of the item of this order line”.
Try it yourself
- Create a
Customerstruct withname: Stringandloyalty_points: u32. Addnew(name: &str) -> Selfthat starts at 0 points, and a methodadd_points(&mut self, points: u32). Create a customer, add 10 points twice, and print them with{:?}.
Show solution
#[derive(Debug)]struct Customer { name: String, loyalty_points: u32,}
impl Customer { fn new(name: &str) -> Self { Self { name: String::from(name), loyalty_points: 0 } }
fn add_points(&mut self, points: u32) { self.loyalty_points += points; }}
fn main() { let mut alex = Customer::new("Alex"); alex.add_points(10); alex.add_points(10); println!("{alex:?}");}Customer { name: "Alex", loyalty_points: 20 }- Add a method
is_free_drink_ready(&self) -> boolthat returnstruewhen the customer has at least 50 points.
Show solution
impl Customer { fn is_free_drink_ready(&self) -> bool { self.loyalty_points >= 50 }}You can have more than one impl block for the same type, or add this method to the existing one.
Recap
- A struct groups named fields into one custom type. Each filled-in copy is an instance.
- Use
let muton the instance to change any of its fields. #[derive(Debug)]lets you print a struct with{:?}or{:#?}.- Methods live in
implblocks and take&self,&mut selforself. - Associated functions like
newhave noselfand are called withType::name().
What’s next
Structs say “this AND that”. Next, in Enums and Match, you’ll model “this OR that”, like an order that is either waiting, brewing, or ready.
0 of 35 lessons complete