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

Walkthrough

Space play step click any line
Three takeaways
  1. 1The deserialize_with attribute lets you plug field-specific parsing logic into serde's derived Deserialize.
  2. 2Wrapping parse errors with serde::de::Error::custom keeps failures in serde's own error channel.
  3. 3Pairing deserialize_with with default and an Option cleanly models fields that may be absent or blank.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Custom date parsing with serde in Rust — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code