Release notes: Release Nutype 0.4.3 · greyblake/nutype · GitHub
Nutype is a Rust crate that improves the newtype pattern using procedural macros. It adds features like sanitization and validation, ensuring values meet predefined criteria before creation. Unlike the regular newtype pattern, Nutype prevents instantiation of values that violate these constraints.
With the new release it's possible, for example, to define a wrapper around Vec<T>
which is guaranteed:
- To be non empty
- To be sorted
use nutype::nutype;
use std::cmp::Ord;
#[nutype(
validate(predicate = |vec| !vec.is_empty()),
sanitize(with = |mut v| { v.sort(); v }),
derive(Debug, PartialEq, AsRef),
)]
struct SortedNonEmpty<T: Ord>(Vec<T>);
fn main() {
let names = SortedNonEmpty::try_new(vec!["Zeno", "Aristotle", "Plato"]).unwrap();
assert_eq!(names.as_ref(), &["Aristotle", "Plato", "Zeno"]);
}
If you're interested, please check out the full documentation in the README.