Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using return value causes E0499 #78698

Closed
x4e opened this issue Nov 3, 2020 · 3 comments
Closed

Using return value causes E0499 #78698

x4e opened this issue Nov 3, 2020 · 3 comments
Labels
C-bug Category: This is a bug.

Comments

@x4e
Copy link

x4e commented Nov 3, 2020

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)

Playground demo

@x4e x4e added the C-bug Category: This is a bug. label Nov 3, 2020
@x4e
Copy link
Author

x4e commented 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:

let a = 0;
let b = a + 1;

and

let b = 0 + 1;

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
Copy link
Member

Is this a duplicate of #43234?

@x4e
Copy link
Author

x4e commented Nov 3, 2020

I’ll close this as #43234 tracks the same issue

@x4e x4e closed this as completed Nov 3, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
C-bug Category: This is a bug.
Projects
None yet
Development

No branches or pull requests

2 participants