| Crates.io | newtypes |
| lib.rs | newtypes |
| version | 0.2.1 |
| created_at | 2025-12-20 20:31:30.952375+00 |
| updated_at | 2026-01-06 17:39:01.243093+00 |
| description | Macros that ease the implementation of the Newtype pattern |
| homepage | |
| repository | https://forge.cloudsling.dev/CTRLback/rs-newtypes |
| max_upload_size | |
| id | 1996938 |
| size | 40,826 |
The newtypes crate is meant to ease the implementation of the
Newtype
pattern while trying to make as few assumptions as possible.
newtype! MacroThe newtype! macro creates a barebones newtype by wrapping an inner type with
a struct, and, if possible, implementing some extra traits for it.
By default, all declared structs have visibility pub.
use newtypes::newtype;
newtype!(NewTypeName, underlying_type);
// In case we want to automatically derive traits (like serde's
// Serialize or Deserialize):
newtype!(NewTypeName, underlying_type; Trait1, ..., TraitN);
Example:
use newtypes::newtype;
use serde::{Deserialize, Serialize}
newtype!(UserId, u32);
newtype!(GroupId, u32; Serialize, Deserialize);
String:
IMPORTANT: The inner value is private. If there are no constraints on the inner value, then we can rely on
newtype_from!macro to implement theFromandFromStrtraits for us.Otherwise we can choose to implement
From,FromStrandTryFrommanually.
newtype_ord! MacroThe newtype_ord! macro extends the functionality provided with
newtype! by implementing the
PartialOrd and
Ord traits
(when possible).
Example:
use newtypes::newtype_ord;
use serde::{Deserialize, Serialize}
newtype_ord!(Rank, u16);
newtype_ord!(TicketNumber, u16; Serialize, Deserialize);
NOTE: It only works for integers, floating point numbers, and
String.
newtype_unit! MacroThe newtype_unit! macro extends the functionality provided with
newtype_ord! by implementing the
Add,
Sub,
AddAssign,
SubAssign, and
Default traits.
Example:
use newtypes::newtype_unit;
use serde::Deserialize;
newtype_unit!(Weight, f32);
newtype_unit!(Length, f32; Deserialize);
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! MacroThe 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:
use newtypes::{newtype, newtype_from};
newtype!(Weight, f32);
newtype_from!(Weight, f32);
NOTE: It only works for integers, floating point numbers, and
String.