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)
26
27
*[Feature Flags](#feature-flags)
@@ -345,6 +346,46 @@ struct Name(String);
345
346
346
347
It's important to ensure that the type specified in the `error` attribute matches the error type returned by the validation function.
347
348
349
+
## Constants
350
+
351
+
You can mark a type with the `const_fn` flag. In that case, its `new` and `try_new` functions will be declared as `const`:
352
+
353
+
```rust
354
+
#[nutype(
355
+
const_fn,
356
+
derive(Debug),
357
+
validate(greater_or_equal =-273.15),
358
+
)]
359
+
pubstructCelsius(f64);
360
+
```
361
+
362
+
Since `Result::unwrap()` is not allowed in `const` contexts, we must manually handle the `Result` when creating constants. Any attempt to instantiate an invalid `Celsius` at compile time will trigger a compilation error:
Note that `const` works only for stack allocated types.
387
+
If you are dealing with a heap allocated type (e.g. `String`) you should consider using `static` with [`LazyLock`](https://doc.rust-lang.org/beta/std/sync/struct.LazyLock.html).
//! Note that `const` works only for stack allocated types.
440
+
//! If you are dealing with a heap allocated type (e.g. `String`) you should consider using `static` with [`LazyLock`](https://doc.rust-lang.org/beta/std/sync/struct.LazyLock.html).
0 commit comments