You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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:
t.push(expression): borrow t first as mutable (but do nothing), and wait the expression has done.
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:
object.method(expression): evaluate expression first, we can borrow it as immutable many times to calculate something.
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.
The text was updated successfully, but these errors were encountered:
When trying to compile this code:
I got a problem
To correct the code, we must split expression into two line:
I think it would be very inconvenient if such instructions appear in many places.
I think the logic of Rust in above code is:
t
first as mutable (but do nothing), and wait theexpression
has done.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:
Then we can write code more clearly.
This is just my thoughts. If something is not right, please give me some explanation. Thank you.
The text was updated successfully, but these errors were encountered: