2个版本
| 0.1.1 | 2020年1月31日 |
|---|---|
| 0.1.0 | 2019年12月31日 |
1190 in 进程宏
7KB
69 行
either_trait_macro
一个类似于属性的宏,用于实现由either crate中定义的Either特质。如果你的特质为类型A和B都实现了,那么它也会自动为Either<A, B>实现。
用法
在定义特质时,添加属性 #[either_trait]。
示例
use either::Either;
use either_trait_macro::either_trait;
#[either_trait]
/// Apply a function `n` times.
trait Apply {
fn times<T, F>(&self, t: T, f: F) -> T
where
F: Fn(T) -> T;
}
struct Once;
impl Apply for Once {
fn times<T, F>(&self, t: T, f: F) -> T
where
F: Fn(T) -> T,
{
f(t)
}
}
impl Apply for u32 {
fn times<T, F>(&self, t: T, f: F) -> T
where
F: Fn(T) -> T,
{
let mut t = t;
for _ in 0..*self {
t = f(t);
}
t
}
}
let either: Either<Once, u32> = Either::Left(Once);
assert_eq!(either.times(1, |x| x + 2), 3);
局限性
此宏仅支持没有关联常量或关联类型的特质。特质方法的第一个参数必须是 self、&self 或 &mut self。其他参数的类型和返回类型不得包含 Self。
依赖
~1.5MB
~35K SLoC