简体   繁体   English

Rust中的隐含借款

[英]Implicit borrowing in Rust

Below is a code snippet ( playground ) that I tried to run: 下面是我尝试运行的代码段( 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);
}

The error says that "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]`

But I don't see any explicit borrowing being done. 但我没有看到任何明确的借款。 Where exactly is the borrowing done? 借款到底在哪里? And what is borrowed? 借来的是什么? And what is the borrowed content mentioned in the error? 错误中提到的借用内容是什么?

This doesn't happen with primitive types like floats, chars etc. Maybe because values are copied rather than being moved, which is possible only in case of primitives (data structures whose values are completely stored in stack rather than in heap). 原始类型(如浮点数,字符等)不会发生这种情况。可能因为值被复制而不是被移动,这只有在基元(数据结构的值完全存储在堆栈而不是堆中)的情况下才有可能。

Assignments move values in this case. 在这种情况下,分配会移动值。 Basically, let stuff = a[0] attempts to move the value at the 0 th index of vector a , which would leave this index somehow undefined, which isn't allowed in Rust. 基本上, let stuff = a[0]尝试在向量a0个索引处移动该值,这将使该索引以某种方式未定义,这在Rust中是不允许的。 The expression a[0] borrows the value at index zero, because it's syntactic sugar for *a.index(0) , where index returns the borrowed value . 表达式a[0]借用索引零处的值,因为它是*a.index(0)的语法糖,其中index 返回借来的值

This is discussed in the Rust book and in Rust by example in more detail. 这将在Rust书和Rust中通过示例更详细地讨论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM