If I have a type like MyEnum
, how can I map it in cases where not every variant is parameterized?
For example, I\'d like to convert from
I'd create a map
method on your enum:
#[derive(Debug)]
enum MyEnum {
B,
C,
D(T),
}
impl MyEnum {
fn map(self, f: impl FnOnce(T) -> U) -> MyEnum {
use MyEnum::*;
match self {
B => B,
C => C,
D(x) => D(f(x)),
}
}
}
fn main() {
let answer = MyEnum::D(42);
let answer2 = answer.map(|x| x.to_string());
println!("{:?}", answer2);
}
This is similar to existing map
methods, such as Option::map.