Unexpected enum behaviour on cast

Why does the following code (example merely illustrative)

#[allow(dead_code)]
enum MyEnum {
    A = 0x01,
    B = 0x02,
    C = 0x03,
}

struct MyStruct {
    e: MyEnum,
    i: u8,
}

impl MyStruct {
    fn print(&self) {
        Self::print_u8(self.e as u8);
        Self::print_u8(self.i);
    }

    fn print_u8(x: u8) {
        println!("{}", x);
    }
}

fn main() {
    let s = MyStruct{e: MyEnum::A, i: 0x10};
    s.print();
}

gives me the following error?

error[E0507]: cannot move out of borrowed content
  --> test.rs:15:24
   |
15 |         Self::print_u8(self.e as u8);
   |                        ^^^^ cannot move out of borrowed content

error: aborting due to previous error

For more information about this error, try `rustc --explain E0507`.

Why isn’t self.e treated as an u8? What can I do in that situation?

You can’t right now because casting the enum requires you to move it. To fix this you can implement Copy for your enum.

4 Likes

Try borrowing self.e as &self.e.

Meanwhile, you might want to check this out:
https://doc.rust-lang.org/std/mem/fn.discriminant.html
https://doc.rust-lang.org/std/intrinsics/fn.discriminant_value.html

Casting enum to u8 may not work.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.