Rust 中的隐式借用

Implicit borrowing in Rust

下面是我尝试 运行:

的代码片段 (playground)
fn main() {
    let a = vec!["hello".to_string(), "world".to_string()];
    let b = vec![10, 20, 30];

    let c = a[0];
    let d = b[0];

    println!("{:?}", c);
    println!("{:?}", d);
}

错误说 "values can't be moved out of borrowed content":

error[E0507]: cannot move out of borrowed content
 --> src/main.rs:5:13
  |
5 |     let c = a[0];
  |             ^^^^
  |             |
  |             cannot move out of borrowed content
  |             help: consider borrowing here: `&a[0]`

但我没有看到任何明确的借用。借款具体在哪里进行?什么是借来的?还有错误中提到的借用内容是什么?

对于 float、chars 等基本类型不会发生这种情况。可能是因为值被复制而不是被移动,这只有在基本类型(其值完全存储在堆栈中而不是在堆)。

在这种情况下,赋值会移动值。基本上,let stuff = a[0] 尝试移动向量 a 的第 0 索引处的值,这将使该索引不知何故未定义,这在 Rust 中是不允许的。表达式 a[0] 借用索引零处的值,因为它是 *a.index(0) 的语法糖,其中 index returns the borrowed value.

这在 Rust 书中和 Rust by example 中有更详细的讨论。