Closed
Description
I tried this code:
fn main() {
let mut a = A{};
println!("{}", a.increment(a.zero()));
}
struct A {}
impl A {
fn zero(&mut self) -> i32 {
0
}
fn increment(&mut self, i: i32) -> i32 {
i + 1
}
}
I expected to see this happen: the number 1
is printed
Instead, this happened:
error[E0499]: cannot borrow `a` as mutable more than once at a time
--> src/main.rs:3:32
|
3 | println!("{}", a.increment(a.zero()));
| - --------- ^ second mutable borrow occurs here
| | |
| | first borrow later used by call
| first mutable borrow occurs here
If I rewrite it like so it will run fine:
fn main() {
let mut a = A{};
let zero = a.zero();
println!("{}", a.increment(zero));
}
Meta
rustc --version --verbose
:
rustc 1.46.0 (04488afe3 2020-08-24)
binary: rustc
commit-hash: 04488afe34512aa4c33566eb16d8c912a3ae04f9
commit-date: 2020-08-24
host: x86_64-unknown-linux-gnu
release: 1.46.0
LLVM version: 10.0
(Exists in stable, beta and nightly)
Metadata
Metadata
Assignees
Labels
Type
Projects
Milestone
Relationships
Development
No branches or pull requests
Activity
x4e commentedon Nov 3, 2020
a.zero is called before a.increment, and will have finished execution by the time a.increment is called.
From my understanding there is no difference in behaviour between:
and
or the equivalent with function calls.
The compiler seems to think that the reference created by calling a.zero will still be active when a.increment is called, which it won't.
fee1-dead commentedon Nov 3, 2020
Is this a duplicate of #43234?
x4e commentedon Nov 3, 2020
I’ll close this as #43234 tracks the same issue