rust
41 lines · 7 steps
Custom CSV deserialization with serde in Rust
Parsing a CSV of transactions into typed structs, with field renaming, defaults, and a custom money parser.
Explained by
highlit
1use std::error::Error;
2use std::path::Path;
3
4use serde::Deserialize;
5
6#[derive(Debug, Deserialize)]
7struct Transaction {
8 id: u64,
9 #[serde(rename = "date")]
10 booked_at: String,
11 description: String,
12 #[serde(deserialize_with = "parse_cents")]
13 amount: i64,
14 #[serde(default)]
15 reconciled: bool,
16}
17
18fn parse_cents<'de, D>(deserializer: D) -> Result<i64, D::Error>
19where
20 D: serde::Deserializer<'de>,
21{
22 let raw = String::deserialize(deserializer)?;
23 let cleaned = raw.trim().replace(['$', ','], "");
24 let dollars: f64 = cleaned.parse().map_err(serde::de::Error::custom)?;
25 Ok((dollars * 100.0).round() as i64)
26}
27
28fn load_transactions(path: impl AsRef<Path>) -> Result<Vec<Transaction>, Box<dyn Error>> {
29 let mut reader = csv::ReaderBuilder::new()
30 .trim(csv::Trim::All)
31 .flexible(false)
32 .from_path(path)?;
33
34 let mut transactions = Vec::new();
35 for result in reader.deserialize() {
36 let record: Transaction = result?;
37 transactions.push(record);
38 }
39
40 Ok(transactions)
41}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1serde attributes let you map messy external data onto clean, typed fields without hand-written parsing loops.
- 2A deserialize_with function turns any string into a domain value while still routing failures through serde's error channel.
- 3Storing money as integer cents sidesteps the rounding pitfalls of holding currency in floating point.
Related explainers
rust
use std::sync::{Arc, Mutex, MutexGuard}; use std::time::Instant; pub struct TimedGuard<'a, T> {
A self-timing mutex guard in Rust
raii
mutex
deref
Advanced
7 steps
javascript
import { parsePhoneNumberFromString } from 'libphonenumber-js'; export class PhoneValidationError extends Error { constructor(message, code) {
Normalizing phone numbers with typed errors
validation
error-handling
custom-errors
Intermediate
6 steps
typescript
import { Injectable, computed, inject, signal } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { firstValueFrom } from 'rxjs';
Optimistic updates with Angular signals
signals
optimistic-updates
state-management
Intermediate
9 steps
python
import os from datetime import datetime, timezone import jwt
JWT bearer auth as a FastAPI dependency
authentication
jwt
dependency-injection
Intermediate
7 steps
go
package config import ( "fmt"
Loading typed config from environment variables in Go
configuration
environment-variables
type-parsing
Beginner
8 steps
python
import logging import traceback from flask import Blueprint, jsonify, request
Centralized JSON error handling in Flask
error-handling
blueprints
json-api
Intermediate
5 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-csv-deserialization-with-serde-in-rust-explained-rust-640d/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.