Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?

Ideas for versioned serde struct

Goals

  • version external APIs
    • read (write?) data of older versions
  • be agnostic over protocol (but we'll actually use JSON in our examples)

First draft

{
  "version": 2,
  "bla": "foo",
  "blub": 5
}

And inspired by serde issue 1137:

#[derive(...)]
struct JsonStuff {
  bla: String,
  #[serde(added_in = 2)]
  blub: u32
}

How to implement?

Fork serde or something to add attrs?

lolnope

Ugly hack

generate code like

mod v1 {
    #[derive(Deserizalize)]
    struct JsonStuff {
        bla: String,
    }
}
mod v2 {
    #[derive(Deserizalize)]
    struct JsonStuff {
        bla: String,
        blub: u32
    }
}

#[derive(Deserizalize)]
enum JsonStuff {
    #[serde(rename = "1")]
    V1(v1::JsonStuff),
    #[serde(rename = "2")]
    V2(v2::JsonStuff),
}

Inspired by David on reddit and sozu issue 240.

Weird other ideas

  • Read (\w+).schema.json files and generate Rust structs
  • Read (\w+).v(\d+).schema.json files and generate versioned Rust structs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment