gpt4 book ai didi

rust - 从结构 : cannot move out of borrowed content 中获取枚举字段

转载 作者:行者123 更新时间:2023-11-29 07:44:30 31 4
gpt4 key购买 nike

我是 Rust 的新手,正在努力思考所有权/借用的概念。现在,我已将我的代码缩减为这个会出现编译错误的最小代码示例。

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.

我仍然处于一切都是按值(value)复制的心态,在这种心态下做self.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 中复制的东西都必须显式标记 Copy 特征。 Copy 在过去是隐含的,但现在已经改变了 ( 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?

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

  • 为类型推导特征复制(如果适用)
  • 使用/派生Clone (self.color.clone())
  • 返回引用

为了解决这个问题,你为Color派生了Copy:

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

这等同于:

impl Copy for Color {}

关于rust - 从结构 : cannot move out of borrowed content 中获取枚举字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28843931/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com