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

Can't borrow mutably to calculate argument to method with mutable borrow. #37706

Closed
tmccombs opened this issue Nov 11, 2016 · 3 comments
Closed

Comments

@tmccombs
Copy link
Contributor

Consider the following example:

fn f(x: &mut [u8]) -> u8 {
    x[0] = 5;
    1
}

fn g(y: &mut [u8], v: u8) {
    y[1] = v;
}

fn main() {
    let mut a: [u8; 3] = [1,2,3];
    // This works:
    let b = f(&mut a);
    g(&mut a, b);
    // But this doesn't:
    // g(&mut a, f(&mut a));
    println!("{:?}", a);
}

if the g(&mut a, f(&mut a)); line is uncommented the compiler gives the following error:

cannot borrow `a` as mutable more than once at a time
  --> lifetimes.rs:12:22
   |
12 |     g(&mut a, f(&mut a));
   |            -         ^ - first borrow ends here
   |            |         |
   |            |         second mutable borrow occurs here
   |            first mutable borrow occurs here

It seems very odd to me that that line doesn't compile, but if I move the result of the call to f into a temporary variable it does.

Unless I am missing something the borrow in the call to f ends before the call to g starts, so this shouldn't be multiple mutable borrows at the same time.

@KalitaAlexey
Copy link
Contributor

KalitaAlexey commented Nov 11, 2016

@tmccombs It has been fixed. Try to compile it with play.rust-lang.org.

@bluss
Copy link
Member

bluss commented Nov 11, 2016

Current behavior is to evaluate the borrows from left to right. If it would be resolved (it's not resolved yet), it falls under the umbrella of rust-lang/rfcs/issues/811

@bluss bluss closed this as completed Nov 11, 2016
@tmccombs
Copy link
Contributor Author

@KalitaAlexey if you uncomment the line I mentioned it doesn't work on play.rust-lang.org.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants