10 / 35

Core Rust Concepts· 12 min read· Lesson 10 of 35

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

src/main.rs
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);
}
Output
Latte costs 450 cents
Available today? true

Step by step:

  1. struct MenuItem { ... } defines the form. Struct names use UpperCamelCase.
  2. Each field has a name and a type, like price_cents: u32. We store money as whole cents in a u32, which avoids rounding errors.
  3. In main, we create an instance by filling in every field.
  4. 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:

src/main.rs
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);
}
Output
Blueberry Muffin available? false
Now 150 cents

Rust 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:

src/main.rs
#[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:#?}");
}
Output
MenuItem { name: "Latte", price_cents: 450, available: true }
MenuItem {
name: "Latte",
price_cents: 450,
available: true,
}
  1. #[derive(Debug)] is an attribute. It tells the compiler “write the debug-printing code for me”.
  2. {latte:?} uses the debug format on one line.
  3. {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”).

src/main.rs
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);
}
Output
Cheese Scone: $3.75
Available: false

Let’s walk through it:

  1. impl MenuItem { ... } says “these functions belong to MenuItem”.
  2. The first parameter &self means “borrow the instance this method was called on, read-only”. It’s shorthand for self: &MenuItem.
  3. Inside, self.price_cents reads a field of that instance.
  4. mark_sold_out takes &mut self because it changes a field. That’s why scone must be let mut.
  5. You call methods with a dot: scone.price_label(). Rust borrows scone for 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.

src/main.rs
#[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:?}");
}
Output
MenuItem { name: "Tea", price_cents: 250, available: true }
  1. new has no self, so it’s an associated function.
  2. You call it with :: on the type, not on an instance: MenuItem::new(...). You’ve already used one: String::from.
  3. new takes a friendly &str and turns it into an owned String.
  4. 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:

src/main.rs
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());
}
Output
Croissant x3 = 975 cents

Dots chain: self.item.price_cents means “the price of the item of this order line”.

Try it yourself

  1. Create a Customer struct with name: String and loyalty_points: u32. Add new(name: &str) -> Self that starts at 0 points, and a method add_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:?}");
}
Output
Customer { name: "Alex", loyalty_points: 20 }
  1. Add a method is_free_drink_ready(&self) -> bool that returns true when 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 mut on the instance to change any of its fields.
  • #[derive(Debug)] lets you print a struct with {:?} or {:#?}.
  • Methods live in impl blocks and take &self, &mut self or self.
  • Associated functions like new have no self and are called with Type::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

Search lessons

Type to search all lessons.