multi-default-trait-impl

Crates.iomulti-default-trait-impl
lib.rsmulti-default-trait-impl
version0.1.2
sourcesrc
created_at2019-09-06 00:24:51.739122
updated_at2019-09-06 01:14:57.190655
descriptionDefine multiple default implementations for a trait
homepage
repositoryhttps://github.com/hainish/multi-default-trait-impl
max_upload_size
id162626
size8,306
William Budington (Hainish)

documentation

README

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);
}
Commit count: 11

cargo fmt