Nutype 0.4.3 supports generic newtypes now

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.

4 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.