Crates.io | default_fields |
lib.rs | default_fields |
version | 0.1.0 |
source | src |
created_at | 2024-10-08 03:04:09.961342 |
updated_at | 2024-10-08 03:04:09.961342 |
description | A simple derive macro that adds a default getter function for each struct field |
homepage | |
repository | https://github.com/qusuyan/DefaultFields.git |
max_upload_size | |
id | 1400731 |
size | 5,480 |
Simple Rust derive macro that, for each field in the struct, creates a function that returns its default value (requires the struct to extend Default
trait). This is useful if you want to parse struct from JSON and fill in the missing elements with defaults. For example, the following code:
#[derive(Deserialize)]
struct TestObj {
#[serde(default = "TestObj::get_default_field1")]
pub field1: bool,
#[serde(default = "TestObj::get_default_field2")]
pub field2: u64,
#[serde(default = "TestObj::get_default_field3")]
pub field3: String,
}
impl TestObj {
pub fn get_default_field1() -> bool {
true
}
pub fn get_default_field2() -> u64 {
100u64
}
pub fn get_default_field3() -> String {
String::from("test_str")
}
}
can be simplified to:
#[derive(Deserialize, DefaultFields)]
struct TestObj {
#[serde(default = "TestObj::get_default_field1")]
pub field1: bool,
#[serde(default = "TestObj::get_default_field2")]
pub field2: u64,
#[serde(default = "TestObj::get_default_field3")]
pub field3: String,
}
impl Default for TestObj {
fn default -> Self {
Self {
field1: true,
field2: 100u64,
field3: String::from("test_str"),
}
}
}