Crates.io | either_trait_macro |
lib.rs | either_trait_macro |
version | 0.1.1 |
source | src |
created_at | 2019-12-31 14:11:46.496186 |
updated_at | 2020-01-31 05:57:52.952128 |
description | An attribute-like macro to implement traits for Either. |
homepage | https://github.com/AlephAlpha/either_trait_macro |
repository | https://github.com/AlephAlpha/either_trait_macro |
max_upload_size | |
id | 193838 |
size | 8,915 |
An attribute-like macro to implement traits for Either
(defined in either
crate). If your trait is implemented for both type A
and B
, then it is automatically implemented for Either<A, B>
.
When defining a trait, add the attribute #[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);
This macro only supports traits without any associated constant or associated type. The first parameter of a trait method must be self
, &self
or &mut self
. The types of other parameters and the return type must not contain Self
.