You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
*[Breaking constraints with new_unchecked](#breaking-constraints-with-new_unchecked)
@@ -346,6 +347,40 @@ struct Name(String);
346
347
347
348
It's important to ensure that the type specified in the `error` attribute matches the error type returned by the validation function.
348
349
350
+
351
+
## Deriving Traits
352
+
353
+
There are two ways to derive traits for a `nutype`.
354
+
355
+
### `derive`
356
+
357
+
The recommended approach is to use the `derive(..)` attribute within the `#[nutype(..)]` macro:
358
+
359
+
```rust
360
+
#[nutype(derive(Debug))]
361
+
pubstructUsername(String);
362
+
```
363
+
364
+
When using `derive`, `nutype` ensures that the derived traits do not compromise the type's invariants (i.e., validation constraints).
365
+
366
+
However, this approach has a limitation: only a predefined set of traits is supported. Deriving arbitrary third-party traits is not allowed via `derive`.
367
+
368
+
### `derive_unsafe`
369
+
370
+
To overcome this limitation, you can use the `derive_unsafe(..)` attribute (requires the corresponding feature flag to be enabled):
371
+
372
+
```rust
373
+
usederive_more::DerefMut;
374
+
375
+
#[nutype(derive_unsafe(DerefMut))]
376
+
pubstructUsername(String);
377
+
```
378
+
379
+
This enables deriving arbitrary traits, including those from third-party crates.
380
+
However, **use this with caution**: `nutype` cannot verify that these traits preserve the invariants of the type.
381
+
It is the developer’s responsibility to ensure that the derived traits do not introduce ways to bypass validation (e.g., by allowing mutable access to the inner value).
382
+
383
+
349
384
## Constants
350
385
351
386
You can mark a type with the `const_fn` flag. In that case, its `new` and `try_new` functions will be declared as `const`:
0 commit comments