Get enumeration field from structure: cannot exit borrowed content

I am new to Rust and trying to bow my head to the concept of ownership / borrowing. Now I have reduced my code to this minimal code sample that gives a compilation 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 } } 
 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. 

I'm still copied in everything by the value of mindset, where it is completely legal to do self.color , as this will give me a copy of Color . Apparently I'm wrong. I found several other questions about the same error in SO, but could not solve the problem.

As I understand it, the field belongs to someone who owns Display . Since I just borrowed a link to Display , I don't own it. Extracting Color trying to transfer ownership of Color to me, which is not possible since I do not own Display . Is it correct?

How to solve it?

+8
rust borrow-checker
source share
1 answer

I am still in everything that is copied by the mindset value, where it is completely legal to do self.color, as that would bring me a copy of the color. Apparently I'm wrong. I found some other questions about this error in SO, but not a solution to my problem.

Everything that can be copied in rust should be explicitly modified with the Copy sign. Copy was implicit in the past, but it has been changed ( rfc ).

As I understand it, the field belongs to someone who owns the Display. Since I just borrowed a link to the Display, I do not own it. Color extraction is trying to transfer ownership of the Color to me, which is not possible since I do not own the display. Is it correct?

Yes. When you encounter this error, there are three possible solutions:

  • Display the Copy flag for the type (if necessary)
  • Use / self.color.clone() Clone ( self.color.clone() )
  • Link return

To solve this problem, you will get Copy for Color :

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

This is the same as:

 impl Copy for Color {} 
+10
source share

All Articles