How to use csv as a dynamic formatter? #380
-
I am trying to integrate with a javascript library that heavily relies on dynamic string templates serialized. However, the string templates are dirt simple csv formats. While I could use a heavier weapon like templating engines (Handlebars), I'm wondering if csv crate could simply serialize a struct but only for the headers I dynamically decide? For instance: #[derive(Debug, Serialize)]
#[serde(rename_all = "PascalCase")]
struct Rec<'a> {
city: &'a str,
state: &'a str,
population: Option<u64>,
latitude: f64,
longitude: f64,
}
fn run() -> Result<(), Box<dyn Error>> {
// "with_headers" is a hypothetical builder method I'm making up that would filter down the set of struct fields to print
let mut wtr = csv::Writer::from_writer(io::stdout()).with_headers(["city", "state"]);
wtr.serialize(Record {
city: "Davidsons Landing",
state: "AK",
population: None,
latitude: 65.2419444,
longitude: -165.2716667,
})?;
wtr.flush()?;
// should print: "city,state\nDavisons Landing,AK"
Ok(())
}
fn main() {
if let Err(err) = run() {
println!("{}", err);
process::exit(1);
}
} Alternatively, I could accomplish this using a proc macro library that converts the struct to a map and then simply filter the keys dynamically. Then I could simply join the keys/values into a string myself, or maybe investigate serializing a map based on this discussion: #98 I guess I'm just posting here because I feel there's a bit of a gap in features rust currently supports between static I'm also curious to know how wildly difficult and out of scope it would be to try and dynamically decide which struct fields get serialized. In general, dynamic formatting minimally just interests me when a compiled language like Rust can pull it off still - even with some hackery. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I don't think a feature like this is a good fit for this library. It's too niche and dependent on serde workflows IMO. For something like this, especially when you're talking about writing proc macros and what not, it makes sense to just bite the bullet and write your own Serde |
Beta Was this translation helpful? Give feedback.
I don't think a feature like this is a good fit for this library. It's too niche and dependent on serde workflows IMO. For something like this, especially when you're talking about writing proc macros and what not, it makes sense to just bite the bullet and write your own Serde
Serializer
. This is howcsv
works internally. It doesn't use any special magic. It's using only public APIs oncsv::Writer
. You could even copy the serializer out ofcsv
and modify it to fit your needs.