47

I have an enum:

enum Foo {
    Bar = 1,
}

How do I convert a reference to this enum into an integer to be used in math?

fn f(foo: &Foo) {
    let f = foo as u8;  // error[E0606]: casting `&Foo` as `u8` is invalid
    let f = foo as &u8; // error[E0605]: non-primitive cast: `&Foo` as `&u8`
    let f = *foo as u8; // error[E0507]: cannot move out of borrowed content
}
Shepmaster
  • 326,504
  • 69
  • 892
  • 1,159
Vitaly Kushner
  • 8,979
  • 8
  • 32
  • 40

1 Answers1

62

*foo as u8 is correct, but you have to implement Copy because otherwise you would leave behind an invalid reference.

#[derive(Copy, Clone)]
enum Foo {
    Bar = 1,
}

fn f(foo: &Foo) -> u8 {
    *foo as u8
}

Since your enum will be a very lightweight object you should pass it around by value anyway, for which you would need Copy as well.

Shepmaster
  • 326,504
  • 69
  • 892
  • 1,159
A.B.
  • 13,619
  • 2
  • 56
  • 58
  • Expanding on this, without `Copy` the `*foo` is interpreted as moving the pointed-to value out of the shared reference passed to `f`. – dubiousjim Jan 22 '21 at 07:10