deriving_via
This library is a slightly more convenient version of derive_more for newtype pattern.
=> Deriving via
Basic Usage
#[derive(DerivingVia)] and then write the #[deriving] attribute on struct and list the trait you want to derive in it.
simple
Derives From<i32> for D and Display for D.
;
with generics
;
with newtype pattern
If you have more than one field, specify #[underlying] for one.
Note that the other fields require default initialisation by the Default trait.
;
Syntax
Derive DerivingVia and list the traits you want to derive in the #[deriving] attribute.
;
The syntax of <Derive> is defined as follows.
Derive := <Trait> | <Trait>(via = <Type>)
Deriving Via
Using the deriving via feature, it is possible to generate derives from the impl of a base of a multi-layered wrapped type.
DerivingVia uses transitive type coercion for type conversion.
All newtypes must be dereferenceable to the underlying type.
Therefore, DerivingVia automatically generates a Deref trait.
Example
use DerivingVia;
;
;
;
Deref trait works transitive, but how we re-constructs a Self type?
Unfortunately, no convenience mechanism exists in the language,
so it is necessary to teach how to revert using the #[transitive] attribute.
Some trait require #[transitive] attribute (see Available Derives section).
Example
use Display;
use DerivingVia;
;
;
;
Available Derives
;
;
DisplayEqOrdHashserde::Serializeserde::DeserializeInto- additional requirements:
Base: Into<Underlying> - limitations: one hop or
#[transitive]
- additional requirements:
From- additional requirements:
Base: From<Underlying> - limitations: one hop or
#[transitive]
- additional requirements:
TryFrom- additional requirements:
Base: From<Underlying> - limitations: one hop or
#[transitive]
- additional requirements:
FromStr- additional requirements:
Base: From<Underlying> - limitations: one hop or
#[transitive]
- additional requirements:
Add-lile (Add, Sub)- additional requirements:
Base: From<Underlying> - limitations: one hop or
#[transitive]
- additional requirements:
Mul-like (Mul, Div)- additional requirements:
Base: From<Underlying> - limitations: one hop or
#[transitive]
- additional requirements:
Arithmetic(Add, Sub, Mul, Div)- additional requirements:
Base: From<Underlying> - limitations: one hop or
#[transitive]
- additional requirements:
Caveat
DerivingVia using transitive case of Type Coercion. According to rumours, transitive Type Coercion is not fully supported yet.
See: https://doc.rust-lang.org/reference/type-coercions.html#coercion-types