Crates.io | devault |
lib.rs | devault |
version | 0.2.0 |
source | src |
created_at | 2021-07-11 15:12:20.289301 |
updated_at | 2023-11-11 04:22:59.548718 |
description | A more flexible alternative to deriving Default. |
homepage | https://github.com/mitchmindtree/devault |
repository | https://github.com/mitchmindtree/devault.git |
max_upload_size | |
id | 421454 |
size | 24,392 |
A more flexible alternative to deriving Default
.
Deriving Devault
behaves the same as deriving Default
, but includes some 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));
}