下面是我尝试运行的代码片段 ( 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]`
但我没有看到任何明确的借用行为。借款具体是在哪里进行的?借来的是什么? 错误中提到的借用内容是什么?
对于浮点型、字符型等基元类型,不会发生这种情况。可能是因为值是被复制而不是被移动,这仅在基元类型(其值完全存储在堆栈而不是堆中的数据结构)的情况下才可能发生。 .
最佳答案
在这种情况下,赋值会移动值。基本上,let stuff = a[0]
尝试移动向量 a
的第 0
索引处的值,这会以某种方式留下该索引未定义,这在 Rust 中是不允许的。表达式 a[0]
借用索引零处的值,因为它是 *a.index(0)
的语法糖,其中 index
returns the borrowed value .
这在 Rust 书籍和 Rust by example 中进行了更详细的讨论。
关于rust - Rust 中的隐式借用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54957905/