Rust中的隐含借款

问题描述 投票:1回答:1

下面是我试图运行的代码片段(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);
}

该错误表示“值不能从借来的内容中移出”:

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]`

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

原始类型(如浮点数,字符等)不会发生这种情况。可能因为值被复制而不是被移动,这只有在基元(数据结构的值完全存储在堆栈而不是堆中)的情况下才有可能。

rust borrow-checker
1个回答
3
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.