#default #derive #default-value #macro #no-alloc #no-std

macro no-std defew

A new() derive macro for structs

8 releases

new 0.1.15 Mar 15, 2025
0.1.14 Mar 13, 2025

#2200 in Rust patterns

Download history 470/week @ 2025-03-08

470 downloads per month

MIT/Apache

21KB
349 lines

Defew = Default + new()

CI crates.io docs.rs

Creates a new() constructor with specified default values for a struct.

use defew::Defew;

#[derive(Defew)]
struct Data {
    a: i32,
    #[new("ABC")]
    b: &'static str,
    #[new(Some(42))]
    c: Option<u64>,
}

let value = Data::new();
assert_eq!(value.a, 0);
assert_eq!(value.b, "ABC");
assert_eq!(value.c, Some(42));

#[derive(Defew)]
struct Values(#[new] i32, #[new(0.5)] f64);

let value = Values::new(42);
assert_eq!(value.0, 42);
assert_eq!(value.1, 0.5);

Syntax

use defew::Defew;
pub trait Trait<T> {
    fn new(value: T) -> Self;
}

#[derive(Defew)]
#[defew(Trait<T>)] // <- optional Trait for the `::new(..)`.
struct Data<T> {
    a: i32, // <- field without #[new(..)] attribute must have `Default::default()`.
    #[new(42)] // <- #[new(value)] specifies the default `value` for the field.
    b: u64,
    #[new] // <- #[new] specifies that the field is passed to the `::new(..)` constructor.
    c: T,
}

Changelog

See releases page

License

MIT OR Apache-2.0

Dependencies

~185–610KB
~14K SLoC