Skip to content

Unable to de-serialize optional fields #15

@mnpw

Description

@mnpw

A missing field in a .toml file is treated as Option::None when de-serialized using toml crate. When using serde-regex, I'm not able to have this behaviour.

Minimal reproducible example:

# Cargo.toml

[dependencies]
serde = {version = "1", features = ["derive"] }
regex = "1.9.3"
serde_regex = "1.1.0"
toml = "0.7
// main.rs

use regex::Regex;
use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, Serialize, Deserialize)]
struct TimestampString {
    pattern_1: String,
    pattern_2: Option<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
struct TimestampRegex {
    #[serde(with = "serde_regex")]
    pattern_1: Regex,
    #[serde(with = "serde_regex")]
    pattern_2: Option<Regex>,
}

fn main() {
    let timestamps_toml = r#"
pattern_1 = "^\\d{4}-\\d{2}-\\d{2}$"
"#;

    // this works fine
    let t_string: TimestampString = toml::from_str(timestamps_toml).expect("Should not panic!");
    println!("{t_string:?}");

    // this does not work fine
    let t_regex: TimestampRegex = toml::from_str(timestamps_toml).expect("Should not panic!");
    println!("{t_regex:?}");
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions