Introduction
Methods let you attach behavior directly to a struct or enum type, similar to how classes bundle data and functions in object-oriented languages. In Rust, methods are defined inside an impl (implementation) block associated with a specific type, rather than inside the type definition itself. This keeps data definitions separate from behavior while still grouping related functionality together.
Cricket analogy: A player's profile (name, average, strike rate) is like a struct's data, while the coach adds batting drills and shot-selection routines in a separate training block, just as Rust attaches methods to a type via impl instead of inside the struct.
Syntax
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
fn new(width: u32, height: u32) -> Rectangle {
Rectangle { width, height }
}
}Explanation
Inside an impl block, functions that take a self parameter are called methods and are invoked with dot syntax (instance.method()). The receiver can take three forms: &self borrows the instance immutably, &mut self borrows it mutably (allowing modification), and self takes ownership of the instance, consuming it. Functions defined in an impl block without a self parameter are called associated functions; they behave like static methods and are called using the double-colon syntax on the type itself, such as Rectangle::new(...) or String::from(...).
Cricket analogy: A commentator reviewing a scorecard borrows it (&self) without altering it, but the scorer updating runs after each ball borrows mutably (&mut self); calling Rectangle::new is like the ICC issuing a fresh match ball rather than referencing an existing one.
Example
struct Counter {
value: i32,
}
impl Counter {
fn new() -> Counter {
Counter { value: 0 } // associated function, no self
}
fn increment(&mut self) {
self.value += 1; // mutable borrow
}
fn value(&self) -> i32 {
self.value // immutable borrow
}
}
fn main() {
let mut c = Counter::new();
c.increment();
c.increment();
println!("counter = {}", c.value());
}Output
counter = 2Key Takeaways
- Methods are defined inside impl Blockname { ... } and use dot syntax to call.
- &self borrows the instance immutably; &mut self borrows it mutably; self consumes it.
- Associated functions have no self parameter and are called with Type::function().
- A struct or enum can have multiple impl blocks with methods split across them.
- Associated functions are commonly used as constructors, like Rectangle::new().
Practice what you learned
1. Where are methods for a struct defined in Rust?
2. Which self receiver allows a method to modify the fields of the instance it's called on?
3. What distinguishes an associated function from a method in an impl block?
4. In `fn increment(&mut self) { self.value += 1; }`, what does &mut self indicate?
5. Which call correctly uses an associated function to construct a new instance, given `impl Rectangle { fn new(w: u32, h: u32) -> Rectangle { ... } }`?
Was this page helpful?
You May Also Like
Structs in Rust
Structs let you group related values into a single named type with fields you access by name.
Traits in Rust
Traits define shared behavior that types can implement, similar to interfaces in other languages.
Enums in Rust
Enums define a type by enumerating its possible variants, each of which can optionally hold its own data.
Generics in Rust
Generics let you write functions, structs, and enums that work over many types while remaining zero-cost at runtime.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics