`impl` methods
A method in Rust is a function inside an impl block whose first parameter is self, &self, or &mut self. The method is namespaced on the type; it is not looked up on a class or a prototype chain.
Detailed Explanation
You have a struct. You want behaviour that belongs with it: "expire this session", "check this token". In a class-based language you would write those functions inside the class body. In Rust you open an impl Session { ... } block and write them there. The type and the methods can even live in different modules, so long as the impl is in the crate that owns the type (or you are writing a trait impl).
The first parameter is the receiver, and the form you pick is a real decision.
| Receiver | What the method may do | What callers still own |
|---|---|---|
&self | Read the value | The original binding, freely |
&mut self | Read and write | The original binding, but borrowed for the call |
self | Consume the value | Nothing; the value has moved in |
&self is the default you should reach for. &mut self is for mutation. self by value is for methods that transform or destroy the value, such as into_inner or into_iter. There is also Box<Self> and other smart-pointer receivers when you need to take ownership of a heap allocation without moving the inner type out first.
This is not Java's implicit this. Rust makes the borrow visible in the signature, which is how the borrow checker knows that session.expire() cannot run while something else holds a shared reference to session. The method call session.expire() is syntax sugar for Session::expire(&mut session) after autoref and autoderef. Autoderef means you can call a method through Box<Session>, &Session, and so on without writing * by hand.
Why methods exist at all, given that free functions work: namespacing and discoverability. session.expire() reads as an action on a value. Session::expire(&mut session) is the same function, and you still use the Type:: form when the receiver is awkward or when you want to pass the function as a value. Associated functions with no receiver — Session::new — sit in the same impl block and are the Rust equivalent of constructors and static methods.
What it costs: an impl method is statically dispatched and inlined like any other function. You pay nothing extra for writing it as a method rather than a free function. You pay for dynamic dispatch only when the method comes from a dyn Trait. Inherent methods (methods in impl Type, not impl Trait for Type) also cannot be implemented for types you do not own; that is the orphan-adjacent side of "methods live with the type".
When a learner reaches for this: modelling operations on a struct they just defined. Prefer inherent methods for behaviour that is true of the type in every context. Prefer trait methods when several types should answer the same question.
Code Examples
struct Session {
user_id: u64,
expires_at: u64,
}
impl Session {
fn is_expired(&self, now: u64) -> bool {
now >= self.expires_at
}
fn expire(&mut self, now: u64) {
self.expires_at = now;
}
fn into_user_id(self) -> u64 {
self.user_id // `self` is consumed; the Session cannot be used again
}
}
fn main() {
let mut session = Session { user_id: 17, expires_at: 100 };
println!("{}", session.is_expired(50)); // prints: false
session.expire(50);
println!("{}", session.is_expired(50)); // prints: true
println!("{}", session.into_user_id()); // prints: 17
}Common Gotchas
`&mut self` exclusive-borrows the value
you cannot pass `session.field` into `session.method(...)` if the method takes `&mut self` and also needs that field. Copy the field first, or restructure the method to take the field as an argument.
`self` by value ends the value's life
after `session.into_user_id()`, `session` is moved. This is a compile error to use it, not a use-after-free.
Call syntax is sugar
`session.is_expired(now)` and `Session::is_expired(&session, now)` are the same function. Use the UFCS form when inference cannot pick an `impl`.
Inherent `impl`s cannot target foreign types
you cannot write `impl Vec<u8> { fn hex(&self) -> String }` in your crate. Write an extension trait instead.