Crates.io | multi-default-trait-impl |
lib.rs | multi-default-trait-impl |
version | 0.1.2 |
source | src |
created_at | 2019-09-06 00:24:51.739122 |
updated_at | 2019-09-06 01:14:57.190655 |
description | Define multiple default implementations for a trait |
homepage | |
repository | https://github.com/hainish/multi-default-trait-impl |
max_upload_size | |
id | 162626 |
size | 8,306 |
Define multiple default implementations for a trait.
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.
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);
}