+
Skip to content

Nutype 0.6.2 - derive_unsafe

Latest

Choose a tag to compare

@greyblake greyblake released this 30 Jul 06:25
· 14 commits to master since this release
f133db2

What is nutype?

Nutype is a proc macro that adds sanitization_ and validation to newtypes, ensuring values always pass checks.

Changes in v0.6.2

  • [FEATURE] Introduce derive_unsafe(..) attribute to derive any arbitrary trait (requires derive_unsafe feature to be enabled).
  • [FIX] Updated the Rust edition: 2021 → 2024.
  • [FIX] Improved error messages for len_char_max and len_char_min validators. They are now clearer and easier to understand.

derive_unsafe

You can now use the new derive_unsafe(..) attribute to derive arbitrary traits, including third-party ones, which are not known to nutype.

Unlike derive(..), this mechanism bypasses nutype’s internal safety checks, meaning it's possible to violate validation rules at runtime if you're deriving a trait that has methods that instantiate or mutate a value.

It requires derive_unsafe feature flag to be enabled.

Example (do not copy blindly):

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 temperature = LlmTemperature::try_new(1.5).unwrap();

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

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

The takeaway: derive_unsafe gives you raw power—but you’re on your own to ensure your type’s invariants aren't broken.

On that note, have a nice day!.

点击 这是indexloc提供的php浏览器服务,不要输入任何密码和下载