Skip to content

Using return value causes E0499 #78698

Closed
Closed
@x4e

Description

@x4e

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

Activity

added
C-bugCategory: This is a bug.
on Nov 3, 2020
x4e

x4e commented on Nov 3, 2020

@x4e
Author

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

fee1-dead commented on Nov 3, 2020

@fee1-dead
Member

Is this a duplicate of #43234?

x4e

x4e commented on Nov 3, 2020

@x4e
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: This is a bug.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @fee1-dead@x4e

        Issue actions

          Using return value causes E0499 · Issue #78698 · rust-lang/rust