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.
Structs
#[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: trueRun this on your computer — see “Get Started” for setup.
implblocks add methods (taking&self,&mut selforself) 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?
The method takes ownershipThe method can modify the instance it's called onThe method is staticThe method is private
Show answer
Answer: The method can modify the instance it's called on