Answer#
A settings file is a struct on disk. With serde you describe it once and get reading and writing for free. Three decisions make it robust: a Default for first runs, the folder created before the first save, and no panic when the file is missing or damaged.
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"use serde::{Deserialize, Serialize};
use std::fs;
use std::path::Path;
#[derive(Serialize, Deserialize, Debug, PartialEq)]
struct Settings {
dark_mode: bool,
font_size: u32,
recent_files: Vec<String>,
}
impl Default for Settings {
fn default() -> Self {
Settings { dark_mode: false, font_size: 14, recent_files: Vec::new() }
}
}
fn load(path: &Path) -> Settings {
fs::read_to_string(path)
.ok()
.and_then(|text| serde_json::from_str(&text).ok())
.unwrap_or_default() // missing or unreadable file: start with the defaults
}
fn save(path: &Path, s: &Settings) -> std::io::Result<()> {
if let Some(dir) = path.parent() {
fs::create_dir_all(dir)?; // the app's folder does not exist on first run
}
let json = serde_json::to_string_pretty(s).expect("settings are always serializable");
fs::write(path, json)
}
fn main() -> std::io::Result<()> {
let path = std::env::temp_dir().join("rs-forum-settings-demo").join("settings.json");
let mut s = load(&path);
println!("first run: {s:?}");
s.dark_mode = true;
s.recent_files.push("report.txt".into());
save(&path, &s)?;
let again = load(&path);
println!("second run: {again:?}");
assert_eq!(s, again);
println!("{}", fs::read_to_string(&path)?);
fs::remove_dir_all(path.parent().unwrap())
}first run: Settings { dark_mode: false, font_size: 14, recent_files: [] }
second run: Settings { dark_mode: true, font_size: 14, recent_files: ["report.txt"] }
{
"dark_mode": true,
"font_size": 14,
"recent_files": [
"report.txt"
]
}In a real app, replace the temporary folder with your app's folder from the dirs crate (see the thread on where to store settings), save when the user changes something or when the app closes, and write atomically (see the thread on saving safely).
Common mistakes#
- Treating
.ok()as "no problem". Silently using defaults for a damaged file means the next save overwrites the user's real settings; see the thread on damaged settings files. - Adding a field to the struct and breaking old files. See the thread on settings versions.
- Saving on every keystroke or slider move. Save when the change is finished.
Related questions#
JSON, TOML or something else?#
Any serde format works the same way. TOML reads well for files people edit by hand; JSON is the most widely understood. Choose by who edits the file.
Sources#
- serde: https://serde.rs/ (read 2026-12-05)
- serde_json: https://docs.rs/serde_json/ (read 2026-12-05)