serde icon indicating copy to clipboard operation
serde copied to clipboard

serde skip will not skip enum values

Open fneddy opened this issue 2 years ago • 1 comments

general: maybe i did not properly understand the docs, but shouldent #[serde(skip)] skip an enum field on serializasion?

problem: this code panics

expectation: ser should contain the serialized values without the Container::Empty values

example:

use serde::Serialize;


#[derive(Debug, Serialize)]
#[serde(untagged)]
enum Container {
    Value(i64),
    Instruction,
    #[serde(skip)] // unfortunately this does not work
    Empty,
}


#[test]
fn test() {
    let values = vec![
        Container::Value(1),
        Container::Value(2),
        Container::Empty,
        Container::Value(1),
        Container::Empty,
        Container::Instruction,
        Container::Value(1),
    ];
    
    let ser = serde_json::to_value(values).expect("damn");
}

playground

fneddy avatar May 16 '22 07:05 fneddy

The code panics because you are calling expect on the return value. It is not a panic stemming from serde. If you look at the variant documentation, you can see that this is expected:

Never serialize this variant. Trying to serialize this variant is treated as an error.

With the serde traits, a value cannot decide itself to be skipped. Skipping is only possible if a container (like a sequence, map, struct) decides that it doesn't want to serialize a value. But if serialize is called on a value, it either needs to serialize something or return an error, which is the case here. You can achieve your goal by writing a custom serialization for the whole Vec.

jonasbb avatar May 16 '22 20:05 jonasbb