So I've been experimenting with extracting values from enum variants. I have a workable solution, but it seems clumsy and misses what I really want to do. Here's my code and then I'll explain myself:
#[derive(Debug)]
pub enum TypeWrapper {
Alphanum(String),
Letter(char),
Integer(i64),
Floating(f64),
}
impl TypeWrapper {
pub fn util_extract_typewrapper(value: TypeWrapper) -> String {
match value {
TypeWrapper::Alphanum(i) => i,
TypeWrapper::Letter(i) => i.to_string(),
TypeWrapper::Integer(i) => i.to_string(),
TypeWrapper::Floating(i) => i.to_string(),
}
}
}
fn main() {
let something = TypeWrapper::Letter('m');
println!("\n The wrapped up value is: {:?} \n", something);
let value = TypeWrapper::util_extract_typewrapper(something);
println!("\n The value as a String is : {} \n", value);
value.chars().next().unwrap();
println!("\n The value as a char is : {} \n", value);
}
This works, but forces me, in the calling function, to deal with converting the extracted value from String into the actual type wrapped up in the enum variant. What I really want to do is pass a TypeWrapper variable to an extraction function that will then, instead of returning only Strings, return to me the value in the actual type the enum variant is wrapping. So, I'm actually asking two questions here this morning:
-
Disregarding my angst concerning where and when to convert each variant into the given type, is this code okay, or is there a better way to do this?
-
Is there a way for an extraction function to return the value in the actual type the enum variant is wrapping? (I tried using generics and couldn't get past the compiler complaining that it must know the type being returned at compile time.)
Thanks!