either_trait_macro

Crates.ioeither_trait_macro
lib.rseither_trait_macro
version0.1.1
sourcesrc
created_at2019-12-31 14:11:46.496186
updated_at2020-01-31 05:57:52.952128
descriptionAn attribute-like macro to implement traits for Either.
homepagehttps://github.com/AlephAlpha/either_trait_macro
repositoryhttps://github.com/AlephAlpha/either_trait_macro
max_upload_size
id193838
size8,915
(AlephAlpha)

documentation

README

either_trait_macro

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>.

Usage

When defining a trait, add the attribute #[either_trait].

Example

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);

Limitations

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.

Commit count: 10

cargo fmt