Methods and associated functions
Quick answer
An impl block defines functions associated with a type. A method has a self parameter and operates on an instance; an associated function without self is called through the type name and can construct an instance.
Choose how self is received
Use &self for reading, &mut self for changing and self for consuming an instance. Self refers to the implementing type. A function named new is a conventional constructor, not a special language keyword. Methods use dot syntax; associated functions without a receiver use Type::function().
struct Rectangle { width: u32, height: u32 }impl Rectangle { fn new(width: u32, height: u32) -> Self { Self { width, height } } fn area(&self) -> u32 { self.width * self.height }}fn main() { println!("{}", Rectangle::new(4, 3).area()); }Expected stdout (not executed):
12new builds the record; area borrows it to calculate the result. Small inputs avoid overflow here.
struct Counter { value: u32 }impl Counter { fn increment(&mut self) { self.value += 1; }}fn main() { let mut counter = Counter { value: 0 }; counter.increment(); println!("{}", counter.value);}Expected stdout (not executed):
1The method borrows the original counter mutably.
Common mistake
Using self by value for a read-only operation can consume a non-Copy record unnecessarily.
Try it yourself
Add a read-only perimeter method to Rectangle and a mutable reset method to Counter.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Methods and associated functions — practice quiz
Choose one answer per question, then review the explanation.
Which receiver suits a method that reads an instance without consuming it?
Which receiver lets a method change ordinary fields in its instance?
Is `new` a special Rust constructor keyword?