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> {
version,
data: object,
}) {
Ok(d) => d,
Err(d) => {
println!("Error on save: {d}");
return;
}
};
// We can deserialize an owned value even though we serialized a reference
let value: VersionedMessage<Object> = postcard::from_bytes(&data).unwrap();
println!("{value:#?}");
}