The Newtype trait
The Problem
Sometimes you want to wrap a type in a newtype, but you want the newtype implements the same traits as the wrapped type. The Newtype trait helps you to implement the traits of the wrapped type for the newtype automatically.
The Solution
When you define a trait, you can support the Newtype trait and any type that implements the Newtype trait will automatically implement your trait.
use Newtype;
use AsRef;
// Now we can use the `MyTrait` trait for the newtype.
;
;
When to use
You can use the Newtype trait when you want to wrap a type in a newtype and you want the newtype implements ALL the newtype-supported traits of the wrapped type. If you need some traits, you should implement them manually and avoid using the Newtype trait.
Drawbacks
The Newtype trait is not a good solution for the following cases:
- If you want to implement a trait for any type that implements other trait (e.g. every type that implements the
Fancytrait will implement theAwesometrait). only one general implementation for each trait is possible. You can't use theNewtypetrait in this case.
use Newtype;
// it's ok to implement the `Fancy` trait for the `Newtype` trait
// every type that implements the `Fancy` trait will implement the `Awesome` trait
// it's not possible to implement the `Awesome` trait for the `Newtype` trait
Tips
Use derive_more and Newtype macros
You can use the derive_more crate to implement the AsRef, AsMut, and Into traits for the newtype. And you can use the Newtype macro to implement the Newtype trait for the newtype.
use Newtype;
use AsRef;
;
How to implement a trait for &self
If you want to implement a trait for &self, you can use the AsRef trait.
use Newtype;
How to implement a trait for &mut self
If you want to implement a trait for &mut self, you can use the AsMut trait.
use Newtype;
How to implement a trait for self
If you want to implement a trait for self, you can use the Into trait.
use Newtype;
How to implement a trait without self
If you want to implement a trait without self, no extra trait is needed.
use Newtype;
How to combine self, &self or &mut self
If you want to implement a trait for self, &self or &mut self, you can use the Into, AsRef or AsMut traits together.
use Newtype;
Installation
[]
= "0.1"