从结构中获取枚举字段:无法移出借用的内容

Get an enum field from a struct: cannot move out of borrowed content

我是 Rust 的新手,正在尝试围绕 ownership/borrowing 概念进行思考。现在我已经将我的代码缩减为这个给出编译错误的最小代码示例。

pub struct Display {
    color: Color,
}

pub enum Color {
    Blue         = 0x1,
    Red          = 0x4,
}

impl Display {
    fn get_color_value(&self) -> u16 {
        self.color as u16
    }
}
src/display.rs:12:9: 12:13 error: cannot move out of borrowed content
src/display.rs:12         self.color as u16
                          ^~~~
error: aborting due to previous error
Could not compile.

我仍然处于一切都被值复制的心态,在这种心态下做self.color是完全合法的,因为那会让我得到一份Color。显然,我错了。我在 SO 上发现了一些关于这个相同错误的其他问题,但没有解决我的问题。

据我了解,该字段归拥有 Display 的人所有。因为我只借了一个 参考 Display,我不拥有它。正在提取 color 次尝试转让所有权 Color 对我来说,这是不可能的,因为我不拥有 Display。这是正确的吗?

如何解决?

I'm still in the everything is copied by value mindset, where it is perfectly legal to do self.color as that would get me a copy of Color. Apparently, I am wrong. I found some other questions about this same error on SO, but no solution to my issue.

任何可以在 rust 中复制的东西都必须明确带有特征 CopyCopy 在过去是隐含的,但现在已经改变了 (rfc)。

As I understand it, the field is owned by whomever owns the Display. Since I only borrowed a reference to the Display, I don't own it. Extracting color attempts to transfer ownership of the Color to me, which is not possible since I don't own the Display. Is this correct?

是的。当您遇到此错误时,有三种可能的解决方案:

  • 推导类型的特征 Copy(如果适用)
  • Use/derive Clone (self.color.clone())
  • Return 参考

为了解决这个问题,你推导出 Copy for Color:

#[derive(Copy, Clone)]
pub enum Color {
    Blue         = 0x1,
    Red          = 0x4,
}

这等同于:

impl Copy for Color {}