【问题标题】:Can not move out of borrowed content in struct getters [duplicate]无法移出结构吸气剂中的借用内容[重复]
【发布时间】:2019-07-04 19:30:18
【问题描述】:

不清楚为什么借用的引用不能调用函数。

Standard Error

   Compiling playground v0.0.1 (/playground)
warning: unused variable: `a`
  --> src/main.rs:23:9
   |
23 |     let a = Astruct::new(Atype::TypeA, 100);
   |         ^ help: consider prefixing with an underscore: `_a`
   |
   = note: #[warn(unused_variables)] on by default

error[E0507]: cannot move out of borrowed content
  --> src/main.rs:13:14
   |
13 |         Some(self.aType)
   |              ^^^^^^^^^^ cannot move out of borrowed content

error: aborting due to previous error

For more information about this error, try `rustc --explain E0507`.
error: Could not compile `playground`.

To learn more, run the command again with --verbose.
enum Atype {
    TypeA,
    TypeB,
}

struct Astruct {
    pub aType : Atype,
    pub aVal : i32,
}

impl Astruct {
    pub fn getType(&self) -> Option<Atype> {
        Some(self.aType)
    }

    pub fn new(aType: Atype, aVal: i32) -> Astruct {
       Astruct { aType: aType,
                 aVal: aVal}
    }
}

fn main() {
    let a = Astruct::new(Atype::TypeA, 100);

    //println!("Type: {} Val: {}", a.aType, a.aVal);
}

【问题讨论】:

  • 因为您在函数中进行移动操作,所以您无法从借用的内容中移动任何内容。这就像将 gpu 从借来的其他计算机移到您的计算机*。 Copying/Cloning 可以,但我建议您先了解概念和成本
  • 不清楚为什么不让调用者借用值 - Playground
  • 感谢您的意见。
  • 你能提供一些链接,用例子解释这些概念吗?
  • The Rust Book 也许?

标签: rust


【解决方案1】:

您正试图将aType 移出结构Astruct 并从方法getType 中返回它。然而,getType 只借用了Astruct(从&amp;self 可以看到)。因为getType 不拥有Astruct,所以它不能从中移出任何东西。

根据您要执行的操作,您有一些选择:

  1. 使Atype派生CopyClone,这样它就可以复制aType。对我来说,这似乎是您想要做的:
#[derive(Copy, Clone)]
enum Atype {
    TypeA,
    TypeB,
}
  1. getType消费Astruct
pub fn getType(self) -> Option<Atype> {
  Some(self.aType)
}
  1. 使getType 返回对Atype 的引用
pub fn getType(&self) -> Option<&Atype> {
  Some(&self.aType)
}

这些选项中的每一个都有其优点和缺点。

【讨论】:

    猜你喜欢
    • 2019-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-04
    • 2018-10-13
    • 1970-01-01
    • 2018-11-16
    • 2020-09-30
    相关资源
    最近更新 更多