rust
28 lines · 7 steps
Serializing config to JSON in Rust
Turn typed config structs into pretty JSON on disk with serde, skipping empty fields along the way.
Explained by
highlit
1use std::fs::File;
2use std::io::{self, BufWriter};
3use std::path::Path;
4
5use serde::Serialize;
6
7#[derive(Serialize)]
8struct ServerConfig {
9 hostname: String,
10 port: u16,
11 #[serde(skip_serializing_if = "Vec::is_empty")]
12 allowed_origins: Vec<String>,
13 tls: TlsConfig,
14}
15
16#[derive(Serialize)]
17struct TlsConfig {
18 enabled: bool,
19 #[serde(skip_serializing_if = "Option::is_none")]
20 cert_path: Option<String>,
21}
22
23fn write_config(config: &ServerConfig, path: impl AsRef<Path>) -> io::Result<()> {
24 let file = File::create(path)?;
25 let mut writer = BufWriter::new(file);
26 serde_json::to_writer_pretty(&mut writer, config)?;
27 writer.flush()
28}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Deriving Serialize lets serde map struct fields to JSON without hand-written conversion code.
- 2skip_serializing_if keeps output clean by omitting empty or absent optional fields.
- 3Wrapping a File in BufWriter batches writes, but you must flush to guarantee the bytes hit disk.
Related explainers
rust
use std::time::Duration; #[derive(Debug, PartialEq)] pub enum ParseDurationError {
Parsing duration strings safely in Rust
parsing
error-handling
checked-arithmetic
Intermediate
8 steps
javascript
const express = require('express'); const router = express.Router(); router.get('/articles/:slug', async (req, res, next) => {
Conditional GET caching in Express
http-caching
conditional-get
routing
Intermediate
8 steps
rust
use std::time::Duration; #[derive(Debug, Clone, Copy)] pub struct LatencyStats {
Computing latency percentiles in Rust
percentiles
interpolation
closures
Intermediate
6 steps
go
package handlers import ( "net/http"
Custom validators and binding in Gin
validation
struct-tags
error-handling
Intermediate
8 steps
ruby
class ImageNormalizer ORIENTATION_TRANSFORMS = { 1 => ->(img) {}, 2 => ->(img) { img.flop },
Correcting EXIF orientation in Ruby
lookup-table
lambdas
image-processing
Intermediate
7 steps
python
import hashlib from collections import defaultdict from pathlib import Path
Finding duplicate files by size then hash
hashing
file-io
deduplication
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/serializing-config-to-json-in-rust-explained-rust-1439/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.