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
typescript
import { Controller } from '@nestjs/common'; import { MessagePattern, Payload,
Manual RabbitMQ acks in a NestJS controller
microservices
message-queue
acknowledgement
Intermediate
8 steps
rust
use std::convert::TryFrom; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum HttpStatus {
Converting HTTP codes with TryFrom in Rust
enums
error-handling
trait-implementation
Intermediate
8 steps
rust
use axum::{ extract::{Request, State}, http::{HeaderValue, StatusCode}, middleware::Next,
API version headers with Axum middleware
middleware
http-headers
versioning
Intermediate
8 steps
rust
use axum::{ extract::Path, http::StatusCode, routing::{get, post},
Building a REST resource in Axum
rest-api
routing
serialization
Intermediate
9 steps
python
import uuid from pathlib import Path from fastapi import APIRouter, File, Form, HTTPException, UploadFile
Handling multipart file uploads in FastAPI
file-upload
validation
multipart-form
Intermediate
6 steps
rust
use axum::{extract::State, http::StatusCode, Json}; use serde::{Deserialize, Serialize}; use sqlx::PgPool; use uuid::Uuid;
An atomic money transfer handler in Axum
database-transactions
atomicity
error-handling
Intermediate
9 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.