I am trying to deserialize a bunch of CSV files into a sequence of structs with Serde. Am learning both Rust and Serde with the wonderful tutorial on csv.
The CSV files have 1:1 mapping with the types I am trying to create, e.g. consider 2 files:
I'm using serde, but I find that I am writing the same function over and over again, so wanted to see what would be the idiomatic rust (rustic?) way to do this.
let file_path = //path to type1.csv
let mut rdr = csv::Reader::from_path(file_path)?;
for result in rdr.deserialize() {
let type1: Type1 = result?;
// do useful stuff with type1 like add it to a vector
How do I avoid re-writing the same loop for the 2-dozen or so types I need to read and instantiate?
Can I use serde to get a vector of structs rather than using the for loop?
If they are all distinct types, then no. You could probably get away with using a macro if you really did not want to write out all of them. But unless it's an obscene amount, I would just write them all out. Chances are you only have to do it once.