How to map a parametrized enum from a generic type to another?

后端 未结 4 497

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

4条回答
  •  一生所求
    2020-12-10 05:41

    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.

提交回复
热议问题