Using postcard and serde how do I "append" version number?

Using Postcard and serde:

pub fn main()
    #[derive(Debug, serde::Serialize, serde::Deserialize)]
    struct Object
        x       : u16,
        y       : u16,

    //const VERSION: &'static str = "0.0.1";
    const VERSION: f32= 0.1;

    let rect = Object{x: 10, y: 20};

    fn save(object: &Object, version: f32)

        let data = match postcard::to_stdvec(object)
            Ok(d)           => d,
            Err(d)            => {println!("Error on save: {d}"); return;}


So far this is my code, so how would I append the version to the data variable?

What do you mean by "append"? In general you can't just append another message to serialized data without some scheme for detecting where one message ends and the next begins. You generally need a secondary protocol for that.

If you want the version to be included in the serialized data, you can just create a wrapper struct that includes it.

pub fn main() {
    //const VERSION: &'static str = "0.0.1";
    const VERSION: f32 = 0.1;

    let rect = Object { x: 10, y: 20 };

    save(&rect, VERSION);

#[derive(Debug, serde::Serialize, serde::Deserialize)]
struct Object {
    x: u16,
    y: u16,

#[derive(Debug, serde::Serialize, serde::Deserialize)]
struct VersionedMessage<T> {
    version: f32,
    data: T,

fn save(object: &Object, version: f32) {
    // We don't need to clone `object`, because serde implements `Serialize` for references to types that implement `Serialize`
    let data = match postcard::to_stdvec(&VersionedMessage::<&Object> {
        data: object,
    }) {
        Ok(d) => d,
        Err(d) => {
            println!("Error on save: {d}");

    // We can deserialize an owned value even though we serialized a reference
    let value: VersionedMessage<Object> = postcard::from_bytes(&data).unwrap();



VersionedMessage {
    version: 0.1,
    data: Object {
        x: 10,
        y: 20,

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.