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

Logic of borrowing in Rust #46741

Closed
giappi opened this issue Dec 15, 2017 · 2 comments
Closed

Logic of borrowing in Rust #46741

giappi opened this issue Dec 15, 2017 · 2 comments

Comments

@giappi
Copy link

giappi commented Dec 15, 2017

When trying to compile this code:

fn main()
{
    let mut t = vec![0, 1, 2, 3, 4, 5, 6, 7];
    t.push( t.len() );
}

I got a problem

error[E0502]: cannot borrow `t` as immutable because it is also borrowed as mutable
 --> src/main.rs:4:13
  |
4 |     t.push( t.len());
  |     -       ^      - mutable borrow ends here
  |     |       |
  |     |       immutable borrow occurs here
  |     mutable borrow occurs here

error: aborting due to previous error

To correct the code, we must split expression into two line:

let tmp = t.len(); // borrow ends here
t.push(tmp);

I think it would be very inconvenient if such instructions appear in many places.

I think the logic of Rust in above code is:

  1. t.push(expression): borrow t first as mutable (but do nothing), and wait the expression has done.
  2. t.len(): while t is borrowing as mutable, we borrow it again (as immutable) and we can not borrow, because it has already borrowed as mutable.

And I suggest changing logic to:

  1. object.method(expression): evaluate expression first, we can borrow it as immutable many times to calculate something.
  2. do object.method(...) with the result of the expression.
    Then we can write code more clearly.

This is just my thoughts. If something is not right, please give me some explanation. Thank you.

@mattico
Copy link
Contributor

mattico commented Dec 15, 2017

This is Two-Phase borrows: #46037
See also NLL: #43234

@steveklabnik
Copy link
Member

Yup! And since it's not a bug, I'm going to give this a close. Or rather, the bug is already covered by those issues.

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