Methods & Associated Functions
Methods are functions with a self receiver in an impl block. Associated functions have no self - constructors like new are the familiar example.
Busca en todas las páginas de la documentación
Methods are functions with a self receiver in an impl block. Associated functions have no self - constructors like new are the familiar example.
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() {
let r = Rectangle::new(10, 20);
println!("{}", r.area());
}When to reach for this: Grouping behavior with data, builder APIs, and encapsulating invariants on struct mutation.
#[derive(Debug)]
struct Account {
balance: i64,
}
impl Account {
fn open(initial: i64) -> Self {
Self { balance: initial.max(0) }
}
fn deposit(&mut self, amount: i64) {
if amount > 0 { self.balance += amount; }
}
fn balance(&self) -> i64 {
self.balance
}
}
fn main() {
let mut a = Account::open(100);
a.deposit(50);
println!("{:?}", a.balance());
}What this demonstrates:
open is associated function - called as Account::opendeposit mutates through &mut selfbalance reads through &self| Receiver | Meaning |
|---|---|
&self | Immutable borrow |
&mut self | Exclusive mutable borrow |
self | Takes ownership (consuming) |
&self with #[rustfmt::skip] patterns | Rare advanced cases |
impl Blocksimpl Rectangle { /* methods */ }
impl Rectangle { /* more methods - merges conceptually */ }implimpl<T: std::fmt::Display> Pair<T> {
fn show(&self) { println!("{}", self.0); }
}Inherent methods are type-specific. Trait impls provide shared interfaces (Display, etc.).
self vs &self choice wrong - Consuming method when borrow suffices forces moves. Fix: Default to &self.self.x() vs self.x - different namespaces but confusing. Fix: Rename for clarity.Self alias - Self refers to implementing type in impl. Fix: Use Self in constructors returning own type.async fn in trait carefully - Native async traits stabilized in recent Rust. Fix: Follow edition docs for async in traits.
| Alternative | Use When | Don't Use When |
|---|---|---|
Free functions fn f(s: &S) | Behavior not central to type | Method expresses capability clearly |
| Trait impl | Polymorphic interface | Single concrete type only |
| Extension trait pattern | Add methods to foreign types | Orphan rule blocks direct impl |
| Builder struct | Many optional constructor fields | Simple new enough |
Similar, but no this pointer - explicit self parameter with ownership semantics.
Yes. impl Enum { ... } works like structs.
Type alias for the type being implemented in the current impl block.
impl Foo { const BAR: u32 = 1; } - called as Foo::BAR.
Return &self or &mut self from setters for builder fluency (or consume self).
pub fn on private struct is useless outside module. Struct must be pub for external use.
Trait provides default; inherent method preferred when both exist - name resolution rules apply.
Convention: new, default, from_* for constructors.
Yes: fn convert<T>(&self) -> T where ...
Via traits like Add in ops - see Operator Overloading page.
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.
Revisado por Chris St. John·Última actualización: 19 jul 2026