简体   繁体   English

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

[英]How do I convert an enum reference to a number?

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
}

*foo as u8 is correct, but you have to implement Copy because otherwise you would leave behind an invalid reference. *foo as u8是正确的,但你必须实现Copy ,否则你会留下无效的引用。

#[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. 由于你的枚举将是一个非常轻量级的对象,你应该按值传递它,你也需要Copy它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM