Answer#
A settings file outlives your program version. Version 2 must read the file version 1 wrote, and ideally version 1 can still open a file written by version 2. Serde gives you the tools:
#[serde(default)](ordefault = "function") on a field: when the field is missing in the file, use the default instead of failing.- A
versionfield you write yourself: when you read an older version, run code that converts it. - Unknown fields: serde ignores them unless you add
deny_unknown_fields, so a file from a newer version still loads.
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
struct Settings {
#[serde(default = "current_version")]
version: u32,
#[serde(default = "default_font")]
font_size: u32,
// added in version 2; files written by version 1 do not have it
#[serde(default)]
dark_mode: bool,
}
fn current_version() -> u32 { 2 }
fn default_font() -> u32 { 14 }
fn migrate(mut s: Settings) -> Settings {
if s.version < 2 {
s.dark_mode = false; // decide what the new field means for old files
s.version = 2;
}
s
}
fn main() {
let old = r#"{ "version": 1, "font_size": 18 }"#;
let s: Settings = serde_json::from_str(old).unwrap();
println!("read: {s:?}");
println!("migrated: {:?}", migrate(s));
// A file with a field this version does not know (written by a newer version) is still read:
let newer = r#"{ "version": 2, "font_size": 12, "dark_mode": true, "sidebar": "left" }"#;
println!("newer: {:?}", serde_json::from_str::<Settings>(newer).unwrap());
}read: Settings { version: 1, font_size: 18, dark_mode: false }
migrated: Settings { version: 2, font_size: 18, dark_mode: false }
newer: Settings { version: 2, font_size: 12, dark_mode: true }Rules of thumb:
- Adding a field: give it a default. No version bump is needed unless the old files need conversion.
- Renaming a field:
#[serde(alias = "old_name")]reads the old name; you write the new one. - Changing the meaning of a field (a number of pixels becomes a percentage): bump
versionand convert inmigrate. - Never reuse a name for a field with a different meaning.
Common mistakes#
- Forgetting that the version in the file is what you read, not the program's version. The program writes its own version when it saves.
- A newer version saving over a file and dropping the fields an older version added. Accept this, or keep unknown fields (for example in a
serde_json::Valuemap) when you rewrite the file.
Related questions#
Can I test migrations?#
Yes, and you should: keep a sample file from each past version in your tests and assert what migrate returns.
Sources#
- serde attributes: https://serde.rs/attributes.html (read 2026-12-05)