Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Option fields require explicit default attribute if with attribute specified #2878

Open
MaxOhn opened this issue Jan 5, 2025 · 0 comments
Open

Comments

@MaxOhn
Copy link

MaxOhn commented Jan 5, 2025

Usually, the default attribute is not required on Option fields and if such a field is missing it'll just be set as None. If the with attribute is used, however, the default attribute also needs to be specified or the deserialization will fail if the field is missing.

Playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=875ca8186b694b73047655afd75895e6

Expanding the code highlights the differences

  • Neither with nor default attributes: (missing_field does not error for Option)
let __field0 = match __field0 {
    _serde::__private::Some(__field0) => __field0,
    _serde::__private::None => _serde::__private::de::missing_field("field")?,
};
  • with attribute but no default:
let __field0 = match __field0 {
    _serde::__private::Some(__field0) => __field0,
    _serde::__private::None =>
        return _serde::__private::Err(
            <__A::Error as _serde::de::Error>::missing_field("field")
        ),
};
  • Both with and default attributes:
let __field0 = match __field0 {
    _serde::__private::Some(__field0) => __field0,
    _serde::__private::None => _serde::__private::Default::default(),
};

Just like with, deserialize_with also causes this. serialize_with seems to not have any effect though.

I imagine a simple fix would be to use the same private missing_field function rather than <A::Error>::missing_field.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

1 participant