Suggest changing receiver of method when used causing move error
Open
@Bishwas-py is already working on this.
Since Aug 6, 2026.
A-diagnostics
D-lack-of-suggestion
D-papercut
P-low
T-compiler
- Dominant language
- Rust
- Stars
- 119k
- Forks
- 16.1k
- PR merge metrics
- PR metrics pending
Description
Code
struct Bag(Vec<i32>);
impl Bag {
fn total(self) -> i32 {
self.0.iter().sum()
}
}
fn main() {
let bag = Bag(vec![1]);
println!("{}", bag.total());
// The diagnostic points out that `self` consumes `bag`, but for a locally
// defined method it could also mention changing the receiver to `&self` when
// the method does not need ownership.
println!("{:?}", bag.0);
//~^ ERROR borrow of moved value: `bag`
}
Current output
error[E0382]: borrow of moved value: `bag`
--> $DIR/local-by-value-method-receiver.rs:20:22
|
LL | let bag = Bag(vec![1]);
| --- move occurs because `bag` has type `Bag`, which does not implement the `Copy` trait
LL | println!("{}", bag.total());
| ------- `bag` moved due to this method call
...
LL | println!("{:?}", bag.0);
| ^^^^^ value borrowed here after move
|
note: `Bag::total` takes ownership of the receiver `self`, which moves `bag`
--> $DIR/local-by-value-method-receiver.rs:8:14
|
LL | fn total(self) -> i32 {
| ^^^^
Desired output
error[E0382]: borrow of moved value: `bag`
--> $DIR/local-by-value-method-receiver.rs:20:22
|
LL | let bag = Bag(vec![1]);
| --- move occurs because `bag` has type `Bag`, which does not implement the `Copy` trait
LL | println!("{}", bag.total());
| ------- `bag` moved due to this method call
...
LL | println!("{:?}", bag.0);
| ^^^^^ value borrowed here after move
|
note: `Bag::total` takes ownership of the receiver `self`, which moves `bag`
--> $DIR/local-by-value-method-receiver.rs:8:14
|
LL | fn total(self) -> i32 {
| ^^^^
help: consider changing `Bag::total` to not consume `Self`
|
LL | fn total(&self) -> i32 {
| +
Rationale and extra context
We should only provide the suggestion if we've analyzed total to check that it doesn't need to consume Self.
The act is already implied by the current diagnostic.
Other cases
Rust Version
1.97
Anything else?
No response
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Assessment
This issue has not been assessed yet.