This library is a slightly more convenient version of derive_more
for newtype pattern.
#[derive(DerivingVia)]
and then write the #[deriving]
attribute on struct and list the trait you want to derive in it.
Derives From<i32> for D
and Display for D
.
```rust
pub struct D(i32); ```
```rust
pub struct D
If you have more than one field, specify #[underlying]
for one.
Note that the other fields require default initialisation by the Default
trait.
```rust
pub struct Test
Derive DerivingVia
and list the traits you want to derive in the #[deriving]
attribute.
```rust
struct Target(Base); ```
The syntax of <Derive>
is defined as follows.
text
Derive := <Trait> | <Trait>(via = <Type>)
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.
```rust use deriving_via::DerivingVia;
pub struct A(i32);
pub struct B(A);
pub struct C(B);
fn main() { let c = C(B(A(42))); println!("{c}"); // 42 } ```
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).
```rust use std::fmt::Display;
use deriving_via::DerivingVia;
pub struct A(i32);
pub struct B(A);
pub struct C(B);
fn main() { let c = C(B(A(42))) + C(B(A(42))); println!("{c}"); } ```
```rust struct Base(Underlying);
struct Target(Base); ```
Display
Eq
Ord
Hash
serde::Serialize
serde::Deserialize
Into
Base: Into<Underlying>
#[transitive]
From
Base: From<Underlying>
#[transitive]
TryFrom
Base: From<Underlying>
#[transitive]
FromStr
Base: From<Underlying>
#[transitive]
Add
-lile (Add, Sub)
Base: From<Underlying>
#[transitive]
Mul
-like (Mul, Div)
Base: From<Underlying>
#[transitive]
Arithmetic
(Add, Sub, Mul, Div)
Base: From<Underlying>
#[transitive]
DerivingVia using transitive case of Type Coercion. Note that this is not fully supported yet.
See: https://doc.rust-lang.org/reference/type-coercions.html#coercion-types