How do I unwrap an arbitrary number of nested Option types?

后端 未结 3 1426
悲哀的现实
悲哀的现实 2020-12-06 11:42

I\'m trying to write a trait that will allow me to "unwrap" multiple nested Option>>> to a single Option

3条回答
  •  既然无缘
    2020-12-06 12:30

    I solved it with auto traits (optin_builtin_traits), but I'm not sure if this is the best approach:

    #![feature(optin_builtin_traits)]
    
    trait IsOption {}
    impl IsOption for Option {}
    
    auto trait IsSingleOption {}
    impl !IsSingleOption for Option> {}
    
    trait UnwrapOption {
        type Inner;
        fn unwrap_opt(self) -> Option;
    }
    
    impl UnwrapOption for Option
    where
        Self: IsSingleOption,
    {
        type Inner = T;
        fn unwrap_opt(self) -> Option {
            self
        }
    }
    
    impl UnwrapOption for Option
    where
        T: IsOption + UnwrapOption,
    {
        type Inner = ::Inner;
        fn unwrap_opt(self) -> Option {
            match self {
                Some(e) => e.unwrap_opt(),
                None => None,
            }
        }
    }
    
    fn main() {
        let x = Some(Some(Some(1)));
        println!("{:?}", x.unwrap_opt());
        let x = Some(1);
        println!("{:?}", x.unwrap_opt());
    }
    

    playground

提交回复
热议问题