#关联 #枚举 #常量 #推导

无std associated-derive

关联推导宏

2个版本

0.1.1 2021年11月13日
0.1.0 2021年11月12日

#82 in #关联


用于 2 个crate(通过 关联

MIT 许可证

12KB
169

associated-derive

为关联类型提供的推导宏。

使用方法

#[derive(Associated)] 添加到枚举定义中。此宏与结构体或联合体不兼容。

在推导 Associated 时,必须在 #[derive(Associated)] 属性下包含一个 #[associate(Type = associated_type)] 属性,将 associated_type 替换为你想与枚举变体关联的常量类型。

对于枚举的每个变体,都必须包含一个 #[assoc(expr)]#[assoc_const(const_expr)] 属性,将其放在变体之上或内联在变体之前,用 exprconst_expr 替换你想要关联的表达式或值。

示例

#[derive(Associated)]
#[associated(Type = &'static str)]
enum Phonetic {
    #[assoc_const("Alpha")] Alpha,
    #[assoc(&"Bravo")] // #[assoc] requires an expression of type &'static Type
    Bravo = 3 // supports explicit enum discriminants
    // ...
}

Phonetic::Alpha.get_associated() // returns a static lifetime reference to "Alpha"

生成实现

impl associated::Associated for Phonetic {
    type AssociatedType = &'static str;
    fn get_associated(&self) -> &'static Self::AssociatedType {
        match self {
            Phonetic::Alpha => {
                const ASSOCIATED: &'static str = "Alpha";
                &ASSOCIATED 
            },
            Phonetic::Bravo => &"Bravo",
        }
    }
}

注意

如果您为一个变体同时赋予了一个 #[assoc] 和一个 #[assoc_const] 属性,或者多个 #[assoc]#[assoc_const] 属性,只有第一个会被考虑。目前包含多个属性并不是错误,但这种情况将会改变,因此每个变体只使用一个 #[assoc]#[assoc_const] 属性。

有关检索关联常量的信息,请参阅 associated

依赖项

~1.5MB
~35K SLoC