rust
42 lines · 7 steps
Custom date parsing with serde in Rust
A Transaction struct wires custom serde deserializers to turn US-format date strings into typed NaiveDate values while reading a CSV.
Explained by
highlit
1use chrono::NaiveDate;
2use serde::{Deserialize, Deserializer};
3
4#[derive(Debug, Deserialize)]
5struct Transaction {
6 id: u64,
7 description: String,
8 #[serde(deserialize_with = "deserialize_us_date")]
9 posted_on: NaiveDate,
10 #[serde(deserialize_with = "deserialize_us_date_opt", default)]
11 cleared_on: Option<NaiveDate>,
12 amount_cents: i64,
13}
14
15fn deserialize_us_date<'de, D>(deserializer: D) -> Result<NaiveDate, D::Error>
16where
17 D: Deserializer<'de>,
18{
19 let raw = String::deserialize(deserializer)?;
20 NaiveDate::parse_from_str(raw.trim(), "%m/%d/%Y").map_err(serde::de::Error::custom)
21}
22
23fn deserialize_us_date_opt<'de, D>(deserializer: D) -> Result<Option<NaiveDate>, D::Error>
24where
25 D: Deserializer<'de>,
26{
27 let raw = String::deserialize(deserializer)?;
28 let trimmed = raw.trim();
29 if trimmed.is_empty() {
30 return Ok(None);
31 }
32 NaiveDate::parse_from_str(trimmed, "%m/%d/%Y")
33 .map(Some)
34 .map_err(serde::de::Error::custom)
35}
36
37fn read_transactions(path: &str) -> csv::Result<Vec<Transaction>> {
38 let mut reader = csv::ReaderBuilder::new()
39 .trim(csv::Trim::Headers)
40 .from_path(path)?;
41 reader.deserialize().collect()
42}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1The deserialize_with attribute lets you plug field-specific parsing logic into serde's derived Deserialize.
- 2Wrapping parse errors with serde::de::Error::custom keeps failures in serde's own error channel.
- 3Pairing deserialize_with with default and an Option cleanly models fields that may be absent or blank.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
rust
use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Lines, Write};
K-way merge of sorted logs in Rust
binary-heap
k-way-merge
streaming-io
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
rust
use std::f64::consts::PI; #[derive(Debug, Clone, Copy)] pub struct LatLng {
Building geographic bounding boxes in Rust
geospatial
value-types
option
Intermediate
7 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
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/custom-date-parsing-with-serde-in-rust-explained-rust-bdd0/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.