Default value for a field
use serde::Deserialize;
#[derive(Deserialize, Debug)]
struct Request {
#[serde(default = "default_resource")]
resource: String,
#[serde(default)]
timeout: Timeout,
#[serde(default = "Priority::lowest")]
priority: Priority,
}
fn default_resource() -> String {
"/".to_string()
}
#[derive(Deserialize, Debug)]
struct Timeout(u32);
impl Default for Timeout {
fn default() -> Self {
Timeout(30)
}
}
#[derive(Deserialize, Debug)]
enum Priority { ExtraHigh, High, Normal, Low, ExtraLow }
impl Priority {
fn lowest() -> Self { Priority::ExtraLow }
}
fn main() {
let json = r#"
[
{
"resource": "/users"
},
{
"timeout": 5,
"priority": "High"
}
]
"#;
let requests: Vec<Request> = serde_json::from_str(json).unwrap();
println!("{:?}", requests[0]);
println!("{:?}", requests[1]);
}