#const #default #fallback

macro devault

A more flexible alternative to deriving Default

2 unstable releases

0.2.0 Nov 11, 2023
0.1.0 Jul 11, 2021

#2082 in Procedural macros

Download history 1011/week @ 2024-07-21 1310/week @ 2024-07-28 858/week @ 2024-08-04 717/week @ 2024-08-11 825/week @ 2024-08-18 593/week @ 2024-08-25 422/week @ 2024-09-01 707/week @ 2024-09-08 1058/week @ 2024-09-15 721/week @ 2024-09-22 477/week @ 2024-09-29 587/week @ 2024-10-06 570/week @ 2024-10-13 1812/week @ 2024-10-20 980/week @ 2024-10-27 720/week @ 2024-11-03

4,090 downloads per month
Used in 2 crates

MIT/Apache

19KB
318 lines

devault Actions Status Crates.io Crates.io docs.rs

A more flexible alternative to deriving Default.

Deriving Devault behaves the same as deriving Default, but includes some added benefits.

Added Benefits

devault allows for specifying specific default values for fields, even if Default is not implemented for their respective type.

use devault::Devault;

const C: u32 = 10;

#[derive(Debug, Devault, PartialEq)]
struct Foo {
    a: u8,
    #[devault("1.0")]
    b: f32,
    #[devault("C")]
    c: u32,
    #[devault("Bar(0.5)")]
    d: Bar,
}

#[derive(Debug, PartialEq)]
struct Bar(f32);

fn main() {
    let foo = Foo::default();
    assert_eq!(foo.a, 0);
    assert_eq!(foo.b, 1.0);
    assert_eq!(foo.c, C);
    assert_eq!(foo.d, Bar(0.5));
}

It can be derived for enums too, with the requirement that a default value is provided.

use devault::Devault;

#[derive(Debug, Devault, PartialEq)]
#[devault("Foo::B(128)")]
enum Foo {
    A,
    B(u8),
}

fn main() {
    assert_eq!(Foo::default(), Foo::B(128));
}

devault can generate associated constants and/or functions for constructing a field's default value outside of the Default implementation.

use devault::Devault;

#[derive(Debug, Devault, PartialEq)]
struct Foo {
    #[devault("1.0", constant)]
    a: f32,
    #[devault("10", function)]
    b: u32,
    #[devault("0.5", constant = "INIT_C", function = "start_c")]
    c: f32,
}

#[derive(Debug, Devault, PartialEq)]
#[devault("Bar::B(42)", constant)]
enum Bar {
    A,
    B(u8),
}

fn main() {
    assert_eq!(Foo::DEFAULT_A, 1.0);
    assert_eq!(Foo::default_b(), 10);
    assert_eq!(Foo::INIT_C, 0.5);
    assert_eq!(Foo::start_c(), 0.5);
    assert_eq!(Bar::DEFAULT, Bar::B(42));
}

TODO

  • Support generic types.

Dependencies

~1.5MB
~37K SLoC