pub struct Writer<W: Write> { /* private fields */ }Expand description
Writes CSV data to a std::io::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 delimiter(&mut self, byte: u8) -> &mut Self
pub fn delimiter(&mut self, byte: u8) -> &mut Self
Set the field delimiter byte (default is ,).
use csv::Writer;
let mut w = Writer::new(Vec::new());
w.delimiter(b'\t');
w.write_row(["a", "b", "c"])?;Sourcepub fn flexible(&mut self, yes: bool) -> &mut Self
pub fn flexible(&mut self, yes: bool) -> &mut Self
Enable or disable the field count consistency check.
When false (default), all rows must have the same number of fields.
When true, rows are allowed to vary in width.
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>
Unwrap the writer, flushing any remaining data and returning the underlying writer.