What would be the easiest way to achieve this?
enum E {
A,
B,
C,
}
// Should return "A" for 0, "B" for 1 and "C" for 2
fn convert(i: u32) -> str {
// ???
}
What would be the easiest way to achieve this?
enum E {
A,
B,
C,
}
// Should return "A" for 0, "B" for 1 and "C" for 2
fn convert(i: u32) -> str {
// ???
}
You cannot return a str
, but you can return a &str
. Combine ideas from How do I match enum values with an integer? and 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"));
}
It was necessary to add the #[derive(Debug)]
attribute and define an implementation on the enum:
#[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
}
It can then by used like this:
fn main() {
let s = E::string_from_int(3 as u8);
println!("{}", s);
}