Create newtypes with great convenience.
All types generated by the following macros implement Debug
, Clone
, Eq
, PartialEq
, Ord
, PartialOrd
and Hash
. For Copy
types, the newtype also implements Copy
.
For convenience, each type is also generated with a conditional derive for serde serialisation and deserialisation. This is enabled
with the serde
feature in your own crate, if desired.
In this example, we create a PhoneNumber
newtype wrapper around a string. We use the macro to generate the type,
then implement a new
function for creating it. The inner field of the newtype is only accessible from the same module, so this
ensures that the type can only be created by methods designed to validate and assert that the type is valid.
```rust nova::string!(PhoneNumber);
impl PhoneNumber { pub fn new(input: String) -> PhoneNumber { // An extremely poorly implementation phone number validator. assert_eq!(input.len(), 10);
Self(input)
}
}
fn blah() { let n = PhoneNumber::new("1234567890".tostring()); let m = PhoneNumber::new("1234567890".tostring()); let o = PhoneNumber::new("1234567891".tostring()); asserteq!(n, m); assert_ne!(n, o); assert!(n < o);
// Deref to get a &str
let _s: &str = &*n;
// into_inner to take back the String
let _s = n.into_inner();
} ```
std
libraryuuid::Uuid
typeheapless
to provide Vec
and String
implementationsno_std
environmentsUsually you'll want to enable heapless
functionality when in a no_std
environment. When declaring the crate
in your Cargo.toml
, do it like this:
toml
nova = { version = "0.2", default-features = false, features = ["heapless"] }
This project is licensed under either of
at your option.