Skip to content

Conversation

@greyblake
Copy link
Owner

@greyblake greyblake commented Jul 27, 2025

This pull request brings derive_unsafe which allows to derive any arbitrary trait (just the way one would expect it to be with regular derive(..) without nutype

It's expected to address the following open issues:

Why it's called derive_unsafe?

It's called derive_unsafe because it enables to derive any traits that nutype is not aware of.
So it is developer's responsibility to ensure that the derived traits do not create a loophole to bypass the constraints.
As the rule of thumb avoid using derive_unsafe with traits that:

  • Create a new instance of the type
  • Mutate the value

Example

use derive_more::{Deref, DerefMut};
use nutype::nutype;

#[nutype(
    derive(Debug, AsRef),
    derive_unsafe(Deref, DerefMut),
    validate(greater_or_equal = 0.0, less_or_equal = 2.0)
)]
struct LlmTemperature(f64);

fn main() {
    let mut temprature = LlmTemperature::try_new(1.5).unwrap();

    // This is not what nutype is designed for!
    *temprature = 2.5;

    // OH no, we've just violated the validation rule!
    assert_eq!(temprature.as_ref(), &2.5);
}

TODO

  • Update CHANGELOG
  • Update docs in lib.rs
  • Update docs in README

@greyblake greyblake merged commit ee74cd9 into master Jul 30, 2025
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants