Rust Tutorial · Structs, Enums and Collections · Lesson 13 of 29

Rust Structs and Methods

Group data in structs, add methods and associated functions with impl, and derive common traits.

Create a free account to save this page, take notes and track your progress. Sign in

Structs

A struct with methods
#[derive(Debug, Clone, PartialEq)]
struct Account {
    owner: String,
    balance_cents: i64,
}

impl Account {
    fn new(owner: &str) -> Self {
        Self { owner: owner.to_string(), balance_cents: 0 }
    }

    fn deposit(&mut self, cents: i64) {
        self.balance_cents += cents;
    }

    fn balance(&self) -> f64 {
        self.balance_cents as f64 / 100.0
    }
}

fn main() {
    let mut account = Account::new("Ana");
    account.deposit(2_550);
    println!("{} has {:.2}", account.owner, account.balance());
    println!("{account:?}");
    let copy = account.clone();
    println!("equal: {}", copy == account);
}

Output

Ana has 25.50
Account { owner: "Ana", balance_cents: 2550 }
equal: true

Run this on your computer — see “Get Started” for setup.

  • impl blocks add methods (taking &self, &mut self or self) and associated functions such as constructors (Self::new).
  • #[derive(Debug, Clone, PartialEq)] generates common trait implementations.

Test yourself

What does &mut self in a method mean?

  1. The method takes ownership
  2. The method can modify the instance it's called on
  3. The method is static
  4. The method is private
Show answer

Answer: The method can modify the instance it's called on

Was this page helpful?