【问题标题】:Understanding de-referencing using '*' in rust了解在 rust 中使用 '*' 取消引用
【发布时间】:2019-02-28 20:15:04
【问题描述】:
struct Abc {
    a: i32,
}

fn main() {
    let mut abc = Abc { a: 30 };
    let xyz = &abc;
    let q = *xyz;
}

编译代码出现以下错误:

error[E0507]: cannot move out of borrowed content
  --> src/main.rs:11:13
   |
11 |     let q = *xyz;
   |             ^^^^
   |             |
   |             cannot move out of borrowed content
   |             help: consider using a reference instead: `&*xyz`

请帮助我了解这里出了什么问题。

【问题讨论】:

  • 您能否进一步描述在这个特定示例中让您感到困惑的地方? This section 关于所有权的书可能会帮助您了解正在发生的事情。而且,还有dozens of other questions with that exact same error message
  • 下面的代码可以编译,但是有问题的代码有问题 "fn main() { let mut abc = 10; let xyz = &abc; let q = *xyz; }"
  • @user8070445 数字是Copy 类型,所以它们不会被移动。您的结构在分配给变量时将被移动,因为它不是Copy

标签: syntax reference rust move-semantics borrowing


【解决方案1】:

当你在 Rust 中编写 let a = b; 时,b 的值被移动a,变量 b 不再可用。

在您的情况下,xyz 是对abc 的引用,因此*xyzabc 相同。移动 abc 是一个错误,因为引用 xyz 仍然存在,但现在指向无效内存。

如果您对 i32 这样的数字类型没有发生这种情况感到困惑,那是因为大多数简单的原语都实现了 Copy 特征。这是标记特征,它告诉编译器将值复制到内存中,而不是移动它。对于小型类型,这可能与(有时甚至比)通过引用传递相同的性能。

见:

【讨论】:

    猜你喜欢
    • 2020-09-17
    • 1970-01-01
    • 2021-10-09
    • 2018-08-08
    • 2016-09-28
    • 2022-12-20
    • 2019-12-26
    • 1970-01-01
    • 2023-03-04
    相关资源
    最近更新 更多