Structs
Programming Languages · Rust Control Flow & Ownership · 12 min
Group related values into your own types with struct, and give them methods with impl.
Grouping data with struct
A struct bundles related values under one name. Each value is a field, with a name and a type:
struct Pet {
name: String,
age: u32,
}
Then make one (an instance) by filling in every field:
let pet = Pet { name: String::from("Rex"), age: 3 };
Above
main, define a structBookwith fieldstitle: Stringandpages: u32.In
main, createbookwith the title"Dune"and412pages.
Reading fields with a dot
Get a field with a dot: pet.name, pet.age.
To change a field, the whole instance must be mut:
let mut pet = Pet { name: String::from("Rex"), age: 3 };
pet.age = 4;
Print
Dune has 412 pagesusingbook.titleandbook.pages.Make
bookmutable, setbook.pagesto500, then printNow it has 500 pagesusingbook.pages.
Methods with impl
A method is a function that belongs to a struct. Put it in an impl block. Its first parameter is &self, which means "borrow the instance I'm called on":
impl Pet {
fn birth_year(&self) -> u32 {
2024 - self.age
}
}
Call it with a dot: pet.birth_year().
Add
impl Rectwith a methodarea(&self) -> u32that returnsself.width * self.height.Print
Area: 12by callingrect.area().
Changing with &mut self
A method that changes the instance takes &mut self instead of &self. The instance must be mut to call it:
impl Pet {
fn have_birthday(&mut self) {
self.age += 1;
}
}
Add
impl Counterwith a methodtick(&mut self)that adds 1 toself.count.In
main, callcounter.tick()three times, so it printsCount: 3.
Put it together: a bank account
Build a tiny bank account: one method changes the balance (&mut self), one only reads it (&self).
In an
impl Accountblock, adddeposit(&mut self, amount: i32)that addsamounttoself.balance.Add
report(&self)that prints the owner,has, and the balance, likeSam has 50.In
main, deposit30, then20, then callreport.
More in Rust Control Flow & Ownership
Previous: Ownership · Next: Enums and match