Newtypes
The newtypes crate is meant to ease the implementation of the
Newtype
pattern while trying to make as few assumptions as possible.
To use it, add the following use/import line:
// We have to import all macros at once because the "public" ones rely
// on "private" ones, and it would be too cumbersome to import them one
// by one.
use *;
newtype! Macro
The newtype! macro creates a barebones newtype by wrapping an inner type with
a struct, and, if possible, implementing some extra traits for it.
newtype!;
// In case we want to automatically derive traits (like serde's
// Serialize or Deserialize):
newtype!;
Example:
newtype!;
newtype!;
Implemented traits
- For all:
- For integers:
- For floating point numbers:
- For
String:
IMPORTANT: The
From,FromStrandTryFromtraits are not implemented, and the inner value is private. If there are no constraints on the inner value, then we can rely onnewtype_from!macro to implement theFromandFromStrtraits for us.
newtype_ord! Macro
The newtype_ord! macro extends the functionality provided with
newtype! by implementing the
PartialOrd and
Ord traits
(when possible).
Example:
newtype_ord!;
newtype_ord!;
NOTE: It only works for integers, floating point numbers, and
String.
newtype_unit! Macro
The newtype_unit! macro extends the functionality provided with
newtype_ord! by implementing the
Add,
Sub,
AddAssign,
SubAssign, and
Default traits.
Example:
newtype_unit!;
newtype_unit!;
NOTE: It only works for integers and floating point numbers.
NOTE: It does not implement arithmetic operations beyond addition and subtraction. Doing that properly would require a more complex library focused on dealing with "units" (example: multiplying lengths gives us an area).
newtype_from! Macro
The macro newtype_from! implements the From and FromStr traits for us
in case it's possible.
It has to be used in combination with one of the other ones
(newtype!, newtype_ord!, or
newtype_unit!).
Example:
newtype!;
newtype_unit!;
NOTE: It only works for integers, floating point numbers, and
String.