mirror of
https://github.com/bytedream/serde-inline-default.git
synced 2025-05-09 04:05:12 +02:00
test(examples): add examples
This commit is contained in:
parent
8d1d49150f
commit
6bb8576fa8
29
examples/basic.rs
Normal file
29
examples/basic.rs
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
use serde::Deserialize;
|
||||||
|
use serde_inline_default::serde_inline_default;
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
#[serde_inline_default]
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct Basic {
|
||||||
|
// if using `String` you have to call `.to_string()`
|
||||||
|
#[serde_inline_default("0.0.0.0".to_string())]
|
||||||
|
host: String,
|
||||||
|
// works without specifying the integer type at the end of the value (8080u16)
|
||||||
|
#[serde_inline_default(8080)]
|
||||||
|
port: u16,
|
||||||
|
// expressions are working too
|
||||||
|
#[serde_inline_default(serde_json::json!({}))]
|
||||||
|
random_third_party_type: serde_json::Value,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() -> Result<(), serde_json::Error> {
|
||||||
|
// creating a empty json object to use the default value of all fields
|
||||||
|
let json_object = json!({});
|
||||||
|
let basic: Basic = serde_json::from_value(json_object)?;
|
||||||
|
|
||||||
|
assert_eq!(basic.host, "0.0.0.0".to_string());
|
||||||
|
assert_eq!(basic.port, 8080);
|
||||||
|
assert_eq!(basic.random_third_party_type, json!({}));
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
39
examples/macro_rules.rs
Normal file
39
examples/macro_rules.rs
Normal file
@ -0,0 +1,39 @@
|
|||||||
|
use serde_json::json;
|
||||||
|
macro_rules! simple_macro {
|
||||||
|
(struct $name:ident { $($field:ident: $type:ty $(= $default:expr)?),*$(,)? }) => {
|
||||||
|
#[serde_inline_default::serde_inline_default]
|
||||||
|
#[derive(serde::Deserialize)]
|
||||||
|
struct $name {
|
||||||
|
$(
|
||||||
|
$(
|
||||||
|
#[serde_inline_default($default)]
|
||||||
|
)?
|
||||||
|
$field: $type
|
||||||
|
),*
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() -> Result<(), serde_json::Error> {
|
||||||
|
// `username` and `password` must be set when deserializing as no default value is defined for
|
||||||
|
// them. `secret` not as we're defining a default value for it
|
||||||
|
simple_macro! {
|
||||||
|
struct Example {
|
||||||
|
username: String,
|
||||||
|
password: String,
|
||||||
|
secret: String = "verysecretsecret".to_string()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let json_object = json!({
|
||||||
|
"username": "testuser",
|
||||||
|
"password": "testpassword"
|
||||||
|
});
|
||||||
|
|
||||||
|
let example: Example = serde_json::from_value(json_object)?;
|
||||||
|
assert_eq!(example.username, "testuser");
|
||||||
|
assert_eq!(example.password, "testpassword");
|
||||||
|
assert_eq!(example.secret, "verysecretsecret");
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user