#tuple #macro #generics #variadics

impl_variadics

一个用于生成重复标识等的宏,通常用于为元组实现 trait。

4 个版本

0.3.0 2024 年 5 月 6 日
0.2.0 2024 年 5 月 6 日
0.1.2 2024 年 3 月 24 日
0.1.1 2024 年 3 月 23 日
0.1.0 2024 年 3 月 23 日

1388开发工具


attr-parser-fn 中使用

自定义许可证

11KB
232

Impl Variadic

用于生成可变参数泛型的宏。

语法类似于 quote

示例

impl_variadics! {
    ..4 "T*" => {
        impl<#(#T0),*> Display for TupleDisplay<(#(#T0,)*)>
        where
            #(#T0: Display,)*
        {
            fn fmt(&self, _f: &mut Formatter) -> Result {
                #(self.0.#index.fmt(_f)?;)*
                Ok(())
            }
        }
    };
    /*
    10..20 "Ty*pe" "my_index_*" "and_more_*" => {
        ...
    }
    */
}

它展开为

impl Display for TupleDisplay<()> {
    fn fmt(&self, _f: &mut Formatter) -> Result {
        Ok(())
    }
}
impl<T0> Display for TupleDisplay<(T0,)>
where
    T0: Display,
{
    fn fmt(&self, _f: &mut Formatter) -> Result {
        self.0 .0.fmt(_f)?;
        Ok(())
    }
}
impl<T0, T1> Display for TupleDisplay<(T0, T1)>
where
    T0: Display,
    T1: Display,
{
    fn fmt(&self, _f: &mut Formatter) -> Result {
        self.0 .0.fmt(_f)?;
        self.0 .1.fmt(_f)?;
        Ok(())
    }
}
impl<T0, T1, T2> Display for TupleDisplay<(T0, T1, T2)>
where
    T0: Display,
    T1: Display,
    T2: Display,
{
    fn fmt(&self, _f: &mut Formatter) -> Result {
        self.0 .0.fmt(_f)?;
        self.0 .1.fmt(_f)?;
        self.0 .2.fmt(_f)?;
        Ok(())
    }
}
  • ..4: 最大迭代器计数为 4,从 0 开始。您可以添加下限,例如 2..10
  • "T*": 自定义标识符模式。将所有 * 替换为索引。您可以尝试其他模式,如 "Type" 或 "index_*"。
  • #index: 一个内置迭代器,提供 0 ~ max_index。
  • #length: 一个内置整数,等于迭代器长度。
  • #T0: 自定义标识符。它提供 T0T1T2 ... TN,其中 N 是范围的
    上限减去 2。它对应于模式 T*,将所有 * 替换为 0

依赖关系

~260–710KB
~17K SLoC