BurntSushi / BurntSushi/rust-csv

Write headers with serde when the collection is empty

Open
#161 8 comments 4 reactions 0 assignees View on GitHub
enhancement
Dominant language
Rust
Stars
2k
Forks
257
PR merge metrics
No merged PRs in 30d

Description

On `csv 1.1.1`

When using `serde` to serialize a CSV file, the header is not written in the file if `Writer::serialize()` has not been called. This might seems logical but here is my problem: I'm using a standard format based on CSV which force us to write a file with the headers, even if there is no data associated.

```rust
use csv::*;
use serde::*;

#[derive(Serialize, Deserialize)]
struct Object {
id: u32,
name: &'static str,
}

fn main() {
let object = Object {
id: 1,
name: "some name",
};
let objects: Vec = vec![object]; // XXXXX
let mut writer = WriterBuilder::default()
.has_headers(true)
.from_path("foo.csv")
.unwrap();
for o in objects {
writer.serialize(o).unwrap();
}
}
```
The above program will output the expected file with the header.

```csv
id,name
1,some name
```

But, if you replace the line annotated with `XXXXX` with
```rust
let objects: Vec = vec![];
```

The resulting file will end up completely empty but I'd like to be able to at least produce.
```csv
id,name
```

Obviously, if I never tell the `Writer` object to do anything, nothing will happen. But I was thinking maybe a `Writer::serialize_header()` could be provided? In the above piece of code, I could call `writer.serialize_header()` just above the `for` loop.

Note: I'm not a rockstar of Rust but I'd be fine to try to implement it if you could provide some guidance. But first, I need to be sure I didn't miss a piece of documentation that would do what I want! And also if you're ok about the possibility to add such a new function and the design of the API.

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.