如何将枚举引用转换为数字?

时间:2015-07-11 15:38:08

标签: rust

我有一个枚举:

enum Foo {
    Bar = 1,
}

如何将对此枚举的引用转换为要在数学中使用的整数?

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
}

1 个答案:

答案 0 :(得分:21)

*foo as u8是正确的,但您必须实施Copy,否则您将留下无效的引用。

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

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

由于你的枚举将是一个非常轻量级的对象,你应该按价值传递它,你也需要Copy