如何在声明性宏中生成特征边界?
我有一个具有大量关联类型的特征。我想要一个在 where 子句绑定的两侧使用这些关联类型的函数:
trait Kind {
type A;
type B;
// 20+ more types
}
trait Bound<T> {}
fn example<K1, K2>()
where
K1: Kind,
K2: Kind,
K1::A: Bound<K2::A>,
K1::B: Bound<K2::B>,
// 20+ more bounds
{
}
输入所有边界会有点脆弱,所以我想创建一个宏来生成这个:
fn example<K1, K2>()
where
K1: Kind,
K2: Kind,
how_do_i_write_this!(K1, K2, Bound, [A, B, /* 20+ more types */])
{
}
但是,在 where 子句绑定的右侧调用宏会导致错误:
macro_rules! bound {
() => { std::fmt::Debug };
}
fn another_example()
where
u8: bound!(),
{}
error: expected one of `(`, `+`, `,`, `::`, `;`, `<`, or `{`, found `!`
--> src/lib.rs:7:14
|
7 | u8: bound!(),
| ^ expected one of 7 possible tokens
是否有任何巧妙的宏技巧可以让我干掉这段代码?
我对宏更改的确切位置或参数没意见。例如,生成整个的宏fn是可以接受的。
如果这是不可能的,我可以使用构建脚本,但如果可能,我宁愿将代码放在同一位置。