When does serde use SeqAccess for structs?

When does serde use SeqAccess for structs? We noticed deriving Deserialize for structs has stuff about SeqAccess. just curious about it. it doesn't seem to ignore unknown/extra fields in those cases tho, unless we misread the macro expansion.

You can deserialize a struct from a sequence of field values. For example:

#[derive(Debug, serde::Deserialize)]
struct A {
    a: u32,
    b: u32,
}

fn main() {
    println!("{:?}", serde_json::from_str::<A>("[1,2]"));
}

It produces: Ok(A { a: 1, b: 2 }).

1 Like

Huh, we would not have expected that with json. o.o

So yes, it does fail if you have extra fields. And there's no way to make it ignore those, or even require MapAccess/forbid SeqAccess?

If you’re implementing a Deserializer, you never need to implement SeqAccess if you don’t want to. If a Deserialize implementation calls deserialize_seq you don’t necessarily need to call visit_seq on the visitor. You can call visit_map instead. That said, it’s up to the Deserialize implementation to handle that scenario. I haven’t looked at the common Deserialize implementations to know how that’s handled. I would probably just test it on the types you’re using to see if it works as expected. And create some tests to make sure it continues to work for the types you are using.

An alternative would be to not use serde and just create a custom parser for the data in question. I’ve done this in the past where I felt like the problem I was solving wasn’t a great fit for serde and I didn’t need the compatibility with the rest of the serde ecosystem.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.