#traits #default #define #multiple

macro multi-default-trait-impl

Define multiple default implementations for a trait

3 releases

0.1.2 Sep 6, 2019
0.1.1 Sep 6, 2019
0.1.0 Sep 6, 2019

#204 in #define

29 downloads per month
Used in 2 crates

LGPL-2.1-or-later

9KB
89 lines

Multiple Default Trait Implementations (multi-default-trait-impl)

Define multiple default implementations for a trait.

Latest Version Rust Documentation

This library contains two attribute macros: default_trait_impl which defines a default trait implementation, and trait_impl which uses a default trait implementation you've defined.

This is particularly useful in testing, when many of your mocked types will have very similar trait implementations, but do not want the canonical default trait implementation to use mocked values.

Example

First, define a default trait implementation for the trait Car:

#[default_trait_impl]
impl Car for NewCar {
    fn get_mileage(&self) -> Option<usize> { Some(6000) }
    fn has_bluetooth(&self) -> bool { true }
}

NewCar does not need to be defined beforehand.

Next, implement the new default implementation for a type:

struct NewOldFashionedCar;

#[trait_impl]
impl NewCar for NewOldFashionedCar {
    fn has_bluetooth(&self) -> bool { false }
}


struct WellUsedNewCar;

#[trait_impl]
impl NewCar for WellUsedNewCar {
    fn get_mileage(&self) -> Option<usize> { Some(100000) }
}

This will ensure that our structs use the NewCar defaults, without having to change the canonical Car default implementation:

fn main() {
    assert_eq!(NewOldFashionedCar.get_mileage(), Some(6000));
    assert_eq!(NewOldFashionedCar.has_bluetooth(), false);
    assert_eq!(WellUsedNewCar.get_mileage(), Some(100000));
    assert_eq!(WellUsedNewCar.has_bluetooth(), true);
}

Dependencies

~1.5MB
~35K SLoC