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

default field value #745

Open
benluelo opened this issue Feb 27, 2025 · 3 comments
Open

default field value #745

benluelo opened this issue Feb 27, 2025 · 3 comments

Comments

@benluelo
Copy link

It is possible to have any functionality similar to #[serde(default)]?

@VictorKoenders
Copy link
Contributor

One issue with this is I'm thinking how this is going to interact with encode/decode:

#[derive(Encode, Decode)]
struct Foo {
    a: u32,
    #[bincode(default)]
    b: u32
}

let bytes = bincode::encode_to_vec(&Foo, bincode::config::standard()).unwrap();

What would be in bytes at this point? We can't skip b, there's numerous issues with serde skipping fields without leaving some form of tombstone.

If we're going to introduce tombstones, then we've just re-invented Option<T> and we wouldn't need an attribute like that.

What's the scenario where you'd want #[bincode(default)]?

@benluelo
Copy link
Author

benluelo commented Mar 2, 2025

our main usecase is adding new fields to a structure in a backwards-compatible way. I attempted to implement this manually by just reading more bytes and using the default if it fails due to hitting the end of the stream, but this of course doesn't work since bincode doesn't have any notion of "structs" (if the struct with this manual implementation is nested with another struct, it will read into the following field of the parent struct). I don't think there's a clean way around this, and likely we'll end up versioning our types at the top level with a large enum a la enum Type { V1(TypeV1), V2(TypeV2) }.

@VictorKoenders
Copy link
Contributor

The best way we've found is to indeed do enum Type { V1(TypeV1), V2(TypeV2) } or to append an Option<()> to each struct. We know there's a desire to have backward compatibility for bincode, but we also have no way to implement this technically with how bincode is set up.

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

No branches or pull requests

2 participants