问题描述
我是 Rust 的新手,并试图围绕所有权/借用概念进行思考.现在我已将我的代码简化为这个会出现编译错误的最小代码示例.
pub struct Display {颜色:颜色,}酒吧枚举颜色{蓝色 = 0x1,红色 = 0x4,}impl 显示 {fn get_color_value(&self) ->u16{self.color 为 u16}}
src/display.rs:12:9: 12:13 错误:无法移出借来的内容src/display.rs:12 self.color 作为 u16^~~~错误:由于先前的错误而中止无法编译.
我仍然处于一切都是按价值复制的心态,在这种情况下,执行 self.color
是完全合法的,因为这会给我一份 颜色代码>.显然,我错了.我在 SO 上发现了一些关于相同错误的其他问题,但没有解决我的问题.
据我所知,该字段由拥有 Display
的任何人拥有.因为我只借了一个对 Display
的引用,我不拥有它.提取 color
尝试转移所有权Color
对我来说是不可能的,因为我不拥有 Display
.这是正确的吗?
我该如何解决?
任何可以在 rust 中复制的东西都必须明确地带有 Copy
特性.Copy
过去是隐式的,但已更改(rfc).
据我所知,该领域归拥有显示器的任何人所有.由于我只是借用了对 Display 的引用,因此我不拥有它.提取颜色尝试将颜色的所有权转让给我,这是不可能的,因为我不拥有显示器.这是正确的吗?
是的.当您遇到此错误时,有三种可能的解决方案:
- 为类型派生特征
Copy
(如果适用) - 使用/派生
Clone
(self.color.clone()
) - 返回参考
为了解决这个问题,你为 Color
派生了 Copy
:
#[derive(Copy, Clone)]酒吧枚举颜色{蓝色 = 0x1,红色 = 0x4,}
这与:
impl Copy for Color {}
I'm new to Rust and trying to wrap my head around the ownership/borrowing concept. Now I have reduced my code to this minimal code sample that gives a compile error.
pub struct Display {
color: Color,
}
pub enum Color {
Blue = 0x1,
Red = 0x4,
}
impl Display {
fn get_color_value(&self) -> u16 {
self.color as u16
}
}
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.
As I understand it, the field is owned by whomever owns the Display
. Since I only borrowed areference to the Display
, I don't own it. Extracting color
attempts to transfer ownership ofthe Color
to me, which is not possible since I don't own the Display
. Is this correct?
How do I solve it?
Anything that can be copied in rust must be explicitly mared with a trait Copy
. Copy
was implicit in the past but that was changed (rfc).
Yes. When you encounter this error there are three possible solutions:
- Derive the trait
Copy
for the type (if appropriate) - Use/derive
Clone
(self.color.clone()
) - Return a reference
To solve this you derive Copy
for Color
:
#[derive(Copy, Clone)]
pub enum Color {
Blue = 0x1,
Red = 0x4,
}
This is the same as:
impl Copy for Color {}
这篇关于从结构中获取枚举字段:无法移出借用的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!