rust - 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, compile error. borrow checker , possibly mutability.

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

yet, if change allowed this:

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

why? there way change can written in 1 line? (p.s. on rust 1.0)

this unfortunate shortcoming of rust borrow checking procedure. happens because

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

is equivalent to

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

and here can see because arguments computed in left-to-right order, result indeed borrowed mutably before used in result.len().

i found problem in rust issue tracker: #6268. issue closed in favor of non-lexical borrows rfc issue. seems it's 1 of things nice have needed more time done available before 1.0. this post may of interest (even though 2 years old).


Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -