不能作为不可变借用 - String 和 len()

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));

但是,这是一个编译错误。与借用检查器和可能的可变性有关。

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

然而,如果我稍作更改,我可以这样做:

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

为什么?有没有办法改变它以便它可以写在一行中? (P.S。这是在 Rust 1.0 上)

这是 Rust 借用检查程序的一个不幸的缺点。这基本上是因为

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

相当于

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

在这里你可以看到,因为参数是按从左到右的顺序计算的,所以 resultresult.len().

中使用之前确实是可变借用的

我在 Rust 问题跟踪器中发现了这个问题:#6268. This issue was closed in favor of non-lexical borrows RFC issue. It seems that it's just one of those things which would be nice to have but which needed more time to be done that it was available before 1.0. This post 可能也有一些兴趣(即使它已经快两年了)。