pub struct Writer<W: Write> { /* private fields */ }Expand description
Writes CSV data to a Write sink.
Fields containing the delimiter, a newline, or a double-quote are
automatically quoted. "" escape sequences are used for quotes
within quoted fields.
Internal buffering is used to avoid many small writes. Callers should
not wrap the writer in a BufWriter.
§Example
use csv::Writer;
let mut w = Writer::new(Vec::new());
w.write_row(["name", "age", "city"])?;
w.write_row(["Alice", "30", "New York, NY"])?;
let result = String::from_utf8(w.into_inner()?).unwrap();
assert_eq!(result, "name,age,city\r\nAlice,30,\"New York, NY\"\r\n");Implementations§
Source§impl<W: Write> Writer<W>
impl<W: Write> Writer<W>
Sourcepub fn new(writer: W) -> Self
pub fn new(writer: W) -> Self
Create a new writer wrapping the given output sink.
The writer starts with default comma delimiter and strict field-count validation (all rows must have the same number of fields).
Sourcepub fn set_delimiter(self, byte: u8) -> Self
pub fn set_delimiter(self, byte: u8) -> Self
Set the field delimiter byte (default is ,).
use csv::Writer;
let mut w = Writer::new(Vec::new()).set_delimiter(b'\t');
w.write_row(["a", "b", "c"])?;Sourcepub fn set_flexible(self, yes: bool) -> Self
pub fn set_flexible(self, yes: bool) -> Self
Set whether variable field counts are allowed (default is false).
When false (strict), all rows must have the same number of fields.
When true, rows may vary in field count.
Sourcepub fn set_headers(self, headers: Vec<String>) -> Self
pub fn set_headers(self, headers: Vec<String>) -> Self
Store column names for schema awareness.
This sets the expected header names for future serde support and strict
field-count validation. It does not write anything to the output.
Use write_headers to emit the header row.
Sourcepub fn write_headers<I, T>(&mut self, headers: I) -> Result<(), WriteError>
pub fn write_headers<I, T>(&mut self, headers: I) -> Result<(), WriteError>
Write a header row to the output and store the column names internally.
The header row is written as a single CSV line. The field count from this row becomes the expected count for all subsequent rows (unless flexible mode is enabled).
If this method has already been called, subsequent calls return
WriteError::HeadersAlreadyWritten.
§Errors
Returns WriteError::HeadersAlreadyWritten if headers have already
been written. Returns WriteError::InconsistentFieldCount if the
number of headers differs from a prior write_row
or from headers stored via set_headers.
Returns WriteError::Io if the underlying writer fails.
Sourcepub fn write_row<I, T>(&mut self, row: I) -> Result<(), WriteError>
pub fn write_row<I, T>(&mut self, row: I) -> Result<(), WriteError>
Write a single row.
Each element in the iterator is written as a CSV field. Fields are
auto-quoted if they contain the delimiter, a newline (\n or \r),
or a double-quote (").
§Errors
Returns WriteError::InconsistentFieldCount if the number of
fields differs from previous rows (unless flexible mode is enabled).
Returns WriteError::Io if the underlying writer fails.
Sourcepub fn flush(&mut self) -> Result<(), WriteError>
pub fn flush(&mut self) -> Result<(), WriteError>
Flush the internal buffer to the underlying writer.
Sourcepub fn into_inner(self) -> Result<W, WriteError>
pub fn into_inner(self) -> Result<W, WriteError>
Flush any remaining data and return the underlying writer.
Source§impl<W: Write> Writer<W>
impl<W: Write> Writer<W>
Sourcepub fn serialize<T: Serialize>(&mut self, record: &T) -> Result<(), WriteError>
pub fn serialize<T: Serialize>(&mut self, record: &T) -> Result<(), WriteError>
Serialize a record and write it as a CSV data row.
Headers must have been set (via set_headers or
write_headers) before calling this method.
For structs, fields are matched by name against the stored headers and written in header column order. For sequences and tuples, elements are written positionally (the field count must equal the header count).
§Errors
Returns WriteError::Serialize if headers have not been set, or if
a serde serialization error occurs (e.g. an unknown field name, or an
unsupported type like a map or enum).
Returns WriteError::InconsistentFieldCount if the number of fields
serialized differs from the expected count (unless flexible mode is
enabled).
Returns WriteError::Io if the underlying writer fails on flush.
§Example
use csv::Writer;
use serde::Serialize;
#[derive(Serialize)]
struct Person {
name: String,
age: u32,
}
let mut w = Writer::new(Vec::new())
.set_headers(vec!["name".into(), "age".into()]);
let alice = Person { name: "Alice".into(), age: 30 };
w.serialize(&alice)?;
let result = String::from_utf8(w.into_inner()?).unwrap();
assert_eq!(result, "Alice,30\r\n");