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 struct Book with fields title: String and pages: u32.

  • In main, create book with the title "Dune" and 412 pages.

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 pages using book.title and book.pages.

  • Make book mutable, set book.pages to 500, then print Now it has 500 pages using book.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 Rect with a method area(&self) -> u32 that returns self.width * self.height.

  • Print Area: 12 by calling rect.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 Counter with a method tick(&mut self) that adds 1 to self.count.

  • In main, call counter.tick() three times, so it prints Count: 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 Account block, add deposit(&mut self, amount: i32) that adds amount to self.balance.

  • Add report(&self) that prints the owner, has, and the balance, like Sam has 50.

  • In main, deposit 30, then 20, then call report.

More in Rust Control Flow & Ownership

Previous: Ownership · Next: Enums and match