How do I convert an enum reference to a number?

前端 未结 1 821
刺人心
刺人心 2021-01-03 17:51

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          


        
1条回答
  •  北荒
    北荒 (楼主)
    2021-01-03 18:48

    *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.

    0 讨论(0)
提交回复
热议问题