Crates.io | optional-default |
lib.rs | optional-default |
version | 0.1.0 |
source | src |
created_at | 2024-07-21 14:20:52.02276 |
updated_at | 2024-07-21 14:20:52.02276 |
description | Helper macro to allow specifying default values for only some of a struct's fields |
homepage | |
repository | |
max_upload_size | |
id | 1310363 |
size | 11,270 |
A Helper macro to allow specifying default values for some fields of a rust struct while requiring some to be initialized manually.
Add optional-default
to your crate's dependencies: cargo add optional-default
OptionalDefault
derive macro.#[optional]
.Default::default()
, or its type does not implement the Default
trait, you can specify your own default value within the #[optional(default = <value>)]
.use optional_default::OptionalDefault;
#[derive(Debug, OptionalDefault)]
struct Example {
foo: i32, // Required field
#[optional]
bar: i32 // Optional, default = i32::default() = 0
#[optional(default = 10)]
baz: i32, // Optional, default = 10
}
fn example() {
// Use the macro as if it was a struct declaration
let example1 = Example! {
foo: 1
// The other fields are set to their default values
};
println!("{:?}", example1); // Example { foo:1, bar: 0, baz: 10 }
let example2 = Example! {
foo: 1,
bar: 5
};
println!("{:?}", example2); // Example { foo:1, bar: 5, baz: 10 }
let example3 = Example! {
foo: 20,
baz: 0 // You can override the default values
};
println!("{:?}", example1); // Example { foo:1, bar: 0, baz: 20 }
let does_not_work = Example! {
baz: 0
}; // Error: missing required field foo
}
Currently, the macro can only be placed on structs. While it would be possible to implement this approach for enums as well, the initialisation syntax would be inconsistent with regular enum initialisations as Enum::Variant
would not be a valid macro name.