rust - Rust 中的隐式借用

标签 rust borrow-checker

下面是我尝试运行的代码片段 ( 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/

相关文章:

sql - 生成 SQL 字符串的 Rust 函数是否容易受到 SQL 注入(inject)的攻击?

csv - 如何反序列化actix Web表单数据并将其序列化为csv文件?

rust - 如何在 Rust 中多线程中使用串口?

rust - 如何模式匹配包含 &mut 枚举的元组并在匹配臂中使用枚举?

shell - 如何使用 entr 在保存时编译和运行 Rust 文件?

memory - Rust 无效指针与 Box::from_raw() Box::into_raw() 往返

generics - 闭包作为 Rust 结构中的一种类型

rust - 为什么不能在同一结构中存储值和对该值的引用?

tree - 我如何反序列化 Rust 中的引用树?

rust - 为什么我不能在同一个结构中存储一个值和对该值的引用?