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

#[serde(default)] behavior for tuples is inconsistent #2529

Closed
Mingun opened this issue Jul 24, 2023 · 1 comment
Closed

#[serde(default)] behavior for tuples is inconsistent #2529

Mingun opened this issue Jul 24, 2023 · 1 comment

Comments

@Mingun
Copy link
Contributor

Mingun commented Jul 24, 2023

Currently, you can define default values for any fields of tuple structs, but at the same time cannot define #[serde(default)] on the type itself, which is inconsistent:

#[derive(Deserialize)]
// #[serde(default)] // Impossible!
struct Newtype(#[serde(default)] u8);

#[derive(Deserialize)]
// #[serde(default)] // Impossible!
struct Tuple(
    #[serde(default)] u8,
    u8,
    #[serde(default)] i8,
);

Actually, the #[serde(default)] on u8 is useless here, because this derive generates the following code:

#[inline]
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
    A: SeqAccess<'de>,
{
    let field0 = match seq.next_element::<u8>()? {
        Some(value) => value,
        None => Default::default(),
    };
    let field1 = match seq.next_element::<u8>()? {
        Some(value) => value,
        None => return Err(Error::invalid_length(1, &"tuple struct Tuple with 3 elements")),
    };
    let field2 = match seq.next_element::<i8>()? {
        Some(value) => value,
        None => Default::default(),
    };
    Ok(Tuple(field0, field1, field2))
}

If you need to use default value for the field, you should also use it for all subsequent fields. So I propose:

  • allow #[serde(default)] on tuples. Currently an error #[serde(default)] can only be used on structs with named fields is produced
  • forbid fields without #[serde(default)] if before them there is a field with #[serde(default)]
    • except when type itself is marked with #[serde(default)]
  • change the error message, because if that would be implemented, then tuples with up to X elements would be allowed
@Mingun
Copy link
Contributor Author

Mingun commented Aug 11, 2023

Fixed by #2553

@Mingun Mingun closed this as completed Aug 11, 2023
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