实现这一目标的最简单方法是什么?
enum E {
A,
B,
C,
}
// Should return "A" for 0, "B" for 1 and "C" for 2
fn convert(i: u32) -> str {
// ???
}
答案 0 :(得分:3)
您无法返回str
,但可以返回&str
。结合How do I match enum values with an integer?和Get enum as string的想法:
#[macro_use]
extern crate strum_macros;
extern crate strum;
use strum::IntoEnumIterator;
#[derive(EnumIter, AsRefStr)]
enum E {
A,
B,
C,
}
fn main() {
let e = E::iter().nth(2);
assert_eq!(e.as_ref().map(|e| e.as_ref()), Some("C"));
}
答案 1 :(得分:-2)
有必要添加#[derive(Debug)]
属性并在枚举上定义一个实现:
#[derive(Debug)]
#[derive(Copy, Clone)]
enum E {
A,
B,
C,
}
impl E {
fn from(t: u8) -> E {
assert(t<=enum_to_int(E::C), "Enum range check failed!");
let el: E = unsafe { std::mem::transmute(t) };
return el;
}
fn to_string(&self) -> String {
return format!("{:?}", self);
}
fn string_from_int(t: u8) -> String {
return E::from(t).to_string();
}
}
fn enum_to_int(el: &E) -> u8 {
*el as u8
}
然后可以像这样使用:
fn main() {
let s = E::string_from_int(3 as u8);
println!("{}", s);
}