代码之家  ›  专栏  ›  技术社区  ›  not 0x12

在Rust中返回枚举的最后一个元素作为默认值

  •  0
  • not 0x12  · 技术社区  · 5 年前

    #[cfg_attr(feature = "std", derive(Debug))]
    #[derive(Clone,  PartialEq, Eq)]
    pub enum Region<CountryId> {
        None,
        Category(CountryId),
    }
    
    #[cfg_attr(feature = "std", derive(Debug))]
    #[derive(Clone, PartialEq, Eq)]
    pub struct Litrature1<CountryId> {
        pub Seek: Region<CountryId>,
        pub Write: Region<CountryId>,
    }
    
    #[cfg_attr(feature = "std", derive(Debug))]
    #[derive(Clone, PartialEq, Eq)]
    pub struct Litrature2<CountryId> {
        pub Seek: Region<CountryId>,
        pub Write: Region<CountryId>,
        pub Work: Region<CountryId>,
    }
    
    #[cfg_attr(feature = "std", derive(Debug))]
    #[derive(Clone,  PartialEq, Eq)]
    pub enum Alphabets<CountryId> {
        A1(Litrature1<CountryId>),
        A2(Litrature1<CountryId>)
    }
    
    
    impl<CountryId> Default for Alphabets<CountryId> {
        fn default() -> Self {
            // How to return the last element of the enum as default?
            Alphabets<CountryId>::A2
        }
    }
    

    Playground

    我不知道该怎么做

    0 回复  |  直到 5 年前
        1
  •  1
  •   loganfsmyth    5 年前

    我假设您本质上希望默认值一直向下,其中每个区域的默认值为 Region::None . 在这种情况下,最有意义的是 Default

    默认值 Region

    impl<CountryId> Default for Region<CountryId> {
        fn default() -> Self {
            Region::None
        }
    }
    

    Litrature1

    impl<CountryId> Default for Litrature1<CountryId> {
        fn default() -> Self {
            Litrature1 {
                Seek: Default::default(),
                Write: Default::default(),
            }
        }
    }
    

    默认值 Litrature2

    impl<CountryId> Default for Litrature2<CountryId> {
        fn default() -> Self {
            Litrature2 {
                Seek: Default::default(),
                Write: Default::default(),
                Work: Default::default(),
            }
        }
    }
    

    默认值 Alphabets

    impl<CountryId> Default for Alphabets<CountryId> {
        fn default() -> Self {
            Alphabets::A2(Default::default())
        }
    }
    

    On the Rust playground