Cannot borrow as immutable - String and len ()

let mut result = String::with_capacity(1000); result.push_str("things... "); result.push_str("stuff... "); result.truncate((result.len() - 4)); 

However, this is a compilation error. Something related to loan verification and possibly variability.

 error[E0502]: cannot borrow `result` as immutable because it is also borrowed as mutable --> <anon>:7:22 | 7 | result.truncate((result.len() - 4)); | ------ ^^^^^^ - mutable borrow ends here | | | | | immutable borrow occurs here | mutable borrow occurs here 

However, if I change this a bit, I am allowed to do this:

 let newlen = result.len() - 4; result.truncate(newlen); 

Why? Is there a way to change this so that it can be written on one line? (PS this is on Rust 1.0)

+7
immutability rust mutability borrow-checker
source share
1 answer

This is an unfortunate flaw in the Rust loan verification procedure. This is because

 result.truncate(result.len() - 2) 

equivalently

 String::truncate(&mut result, result.len() - 2) 

and here you can see that since the arguments are evaluated in order from left to right, the result really borrowed with the change before it is used in result.len() .

I found this problem in the Rust tracker: # 6268 . This issue has been closed in favor of a non-lexical borrowed RFC issue . This seems to be just one of those things that would be nice to have, but that needed more time to be available before 1.0. This post may also be of some interest (although he is almost two years old).

+9
source share

All Articles