Sub topic 8
Methods: self, &self, and &mut self
This chapter assumes you know basic Rust syntax, the rules of ownership and borrowing (move, &, &mut), and how to define a struct with an impl block. Here you will learn what the three receiver forms mean, how to choose between them, and which errors to expect.
What a receiver is
A method is a function inside an impl block whose first parameter is named self. That first parameter is the receiver. It tells the compiler how the method uses the value it is called on.
Inside an impl Rectangle block, the receiver forms are shorthand:
| Written as | Expands to | Meaning |
|---|---|---|
| `self` | `self: Self` | Takes ownership of the value |
| `&self` | `self: &Self` | Borrows the value read-only |
| `&mut self` | `self: &mut Self` | Borrows the value for modification |
Self is an alias for the type named in the impl header. A function in an impl block without a self first parameter is an associated function, not a method. You call it with Type::name(...), as with Rectangle::new.
The three receivers in one type
The following example uses all three forms on one struct.
#[derive(Debug, Clone, PartialEq)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn new(width: u32, height: u32) -> Self {
Self { width, height }
}
fn square(size: u32) -> Self {
Self::new(size, size)
}
fn area(&self) -> u32 {
self.width * self.height
}
fn scale(&mut self, factor: u32) {
self.width *= factor;
self.height *= factor;
}
fn into_dimensions(self) -> (u32, u32) {
(self.width, self.height)
}
}
fn main() {
let mut r = Rectangle::new(3, 4);
println!("area = {}", r.area());
r.scale(2);
println!("{:?}", r);
let sq = Rectangle::square(5);
println!("square area = {}", sq.area());
let (w, h) = r.into_dimensions();
println!("{w}x{h}");
}The program prints area = 12, then Rectangle { width: 6, height: 8 }, then square area = 25, then 6x8.
`&self`: read without taking
Use &self when the method only needs to look at the data. The caller keeps the value, and any number of &self calls can run at the same time on the same value.
area is the typical case. After r.area() returns, r is still fully usable. A &self method can't assign to fields. This line fails to compile:
fn area(&self) -> u32 {
self.width = 0; // error: cannot assign to `self.width`, which is behind a `&` reference
self.width * self.height
}Treat &self as the default. Move to another form only when the method needs more.
`&mut self`: change in place
Use &mut self when the method modifies the value but the caller should keep it. Two conditions apply to the caller:
- The binding must be declared
mut. Callingscaleonlet r = ...is an error. - No other borrow of the value can be alive during the call.
fn main() {
let r = Rectangle::new(1, 1);
r.scale(2); // error: cannot borrow `r` as mutable, as it is not declared as mutable
}The second condition is where beginners often stumble. This fails because first is still in use after the mutable call starts:
fn main() {
let mut r = Rectangle::new(3, 4);
let first = &r.width;
r.scale(2); // error: cannot borrow `r` as mutable because it is also borrowed as immutable
println!("{first}");
}Remove the final println!, or copy the width first with let first = r.width;, and the program compiles. A u32 is Copy, so the copy holds no borrow.
`self`: consume the value
A method that takes self by value moves the receiver into the method. The caller can't use the original afterward. Use this form in three situations:
- The method turns the value into something else, like
into_dimensions. Theinto_prefix is the standard naming convention. - The method hands off ownership of a field, such as returning a
Stringwithout cloning it. - The method represents the end of an object's useful life, such as
buildon a builder orcloseon a connection.
fn main() {
let r = Rectangle::new(2, 3);
let (w, h) = r.into_dimensions();
println!("{w}x{h}");
println!("{}", r.area()); // error: borrow of moved value: `r`
}The compiler points at the into_dimensions call and notes that the method takes ownership of the receiver. If Rectangle implemented Copy, the call would copy the value instead and r would stay usable.
A self method does not need mut on the caller's binding. The value is moved, so the caller isn't mutating anything. If the method body itself needs to modify self, write mut self in the signature. Builders use this form, as in fn port(mut self, port: u16) -> Self.
Choosing a receiver
Ask what the method needs, in this order:
- Does it need to keep or return the value's fields by ownership, or consume the value? Use
self. - Does it modify the value? Use
&mut self. - Otherwise, use
&self.
The choice shapes the method's public contract. Callers can see from the signature whether a call leaves the value alone, changes it, or ends it.
Chaining and return values
A method's return type works with the receiver to give different call styles.
- A
&mut selfmethod that returns nothing is called as a statement:r.scale(2);. - A
self -> Selfmethod can be chained:a.with_x(1).with_y(2). Each call consumes the previous value and returns a new one. - A
&selfmethod can return a reference into the struct. The reference's lifetime is tied to the borrow ofself, so the struct can't be modified or dropped while the reference is in use.
struct User {
name: String,
}
impl User {
fn name(&self) -> &str {
&self.name
}
fn into_name(self) -> String {
self.name
}
}
fn main() {
let u = User { name: String::from("Ada") };
let borrowed = u.name();
println!("{borrowed}");
let owned = u.into_name();
println!("{owned}");
}This compiles because borrowed is last used before u is moved. If you printed borrowed after into_name, the compiler would reject it.
Common errors
| Error message (short form) | Cause | Fix |
|---|---|---|
| cannot borrow as mutable, as it is not declared as mutable | Calling a `&mut self` method on a non-`mut` binding | Declare the binding with `let mut` |
| cannot borrow as mutable because it is also borrowed as immutable | A shared borrow is still alive during a `&mut self` call | Shorten the shared borrow or copy the data out |
| borrow of moved value | A `self` method already consumed the value | Clone first, use a `&self` form, or stop using the original |
| cannot move out of `self.field` which is behind a shared reference | A `&self` method tried to return an owned non-`Copy` field | Return a reference, call `.clone()`, or take `self` |
| cannot assign to `self.field`, which is behind a `&` reference | A `&self` method tried to modify a field | Change the receiver to `&mut self` |
The fourth row appears when you write something like this:
impl User {
fn take_name(&self) -> String {
self.name // error: cannot move out of `self.name` which is behind a shared reference
}
}The fix depends on intent. Return &str if the caller only reads the name. Return self.name.clone() if the caller needs its own copy and the struct must survive. Take self if the struct is done after the call.
Taking `self` by reference to other types
Receivers are not limited to the three shorthand forms. You can also write self: Box<Self>, self: Rc<Self>, or self: Pin<&mut Self>, which are used in specialized code such as trait objects and async. You will rarely need them while learning, so the three shorthand forms cover nearly all everyday code.
A note on mixing forms
One type can mix all three forms, as Rectangle does. A well-designed struct typically has many &self methods, a few &mut self methods, and a small number of self methods. If you find yourself writing mostly self methods on a type that people call repeatedly, check whether &self or &mut self would serve the caller better.
Exercise
A struct Counter { count: u32 } needs three methods: get returns the current count, increment adds 1 to it, and finish returns the final count and ends the counter's use. Which receiver does each method take, and what happens if you call get after finish?
Show answer
get takes &self because it only reads. increment takes &mut self because it modifies count while the caller keeps the counter. finish takes self because it consumes the counter. Calling get after finish fails to compile with "borrow of moved value", because finish moved the Counter into the method. This holds unless Counter implements Copy.
Exercise
This method fails to compile: fn label(&self) -> String { self.label } where label is a String field. Give two valid fixes and say when each is appropriate.
Show answer
Change the return type to &str and return &self.label, which is appropriate when the caller only needs to read the text. Or return self.label.clone(), which is appropriate when the caller needs an owned String and the struct must stay usable. A third option is to change the receiver to self, which suits cases where the struct is no longer needed afterward.