在Rust中将枚举的最后一个元素返回为Default

时间:2019-03-06 22:21:51

标签: rust

我有一个rust实现,如下所示,在默认实现中,对于枚举,我需要返回最后一个元素,并且无需硬编码即可实现它。

#[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

我不确定如何进行这项工作

1 个答案:

答案 0 :(得分:1)

我假设您本质上一直想要默认值,其中每个区域默认为modelBuilder.Properties()。在这种情况下,在每种嵌套类型上定义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

On the Rust playground