我有一个enum:
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
}
*foo as u8
是正确的,但你必须实现Copy
,否则你会留下一个无效的引用。
#[derive(Copy, Clone)]
enum Foo {
Bar = 1,
}
fn f(foo: &Foo) -> u8 {
*foo as u8
}
因为你的enum将是一个非常轻量级的对象,你应该传递它的值,无论如何,你也需要Copy
。
上面的帖子是错误的:
枚举Foo
- 作为名称的变体 Bar
- 和变型号码 1。Rust不需要设置一个数字。但是如果你想检查值,例如从数据库中,使用(和控制)数字而不是名称是有意义的。
如我所知;你需要枚举。枚举变量的value (value)
这是你的例子的一个工作解决方案:
use std::fmt;
#[derive(Debug)]
enum Foo {
Bar = 1,
}
//The to_string() method is available because, Rust automatically implements it for any type that implements Display.
impl fmt::Display for Foo {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self) // or fmt::Debug::fmt(self, f) // prints "Bar" NOT the value
}
}
// here are 2 strings, one for the Variant "Bar" and one for the value "1"
let value_of_foo_bar_enum_as_string:String=(Foo::Bar as i32).to_string();
let enum_variant_as_string:String=Foo::Bar.to_string(); //requires impl fmt::Display for Foo above
println!("Enum Foo: variant ->{}<- has value ->{}<-", Foo::Bar, (Foo::Bar as i32).to_string());
// or
println!("Enum Foo: variant ->{enum_variant_as_string}<- has value ->{value_of_foo_bar_enum_as_string}<-");
// Both prints out "Enum Foo: variant ->Bar<- has value ->1<-
assert_eq!(Foo::Bar.to_string(),"Bar");
assert_eq!((Foo::Bar as i32).to_string(),"1"); // default is i32, can be replaced with u8
玩得开心!马丁