pub fn write_table<Cell: Display, Row: IntoIterator<Item = Cell>, const COLUMN_COUNT: usize>(
to: impl Write,
iter: impl Iterator<Item = Row>,
column_names: &[&str; COLUMN_COUNT],
column_widths: &[NonZeroUsize; COLUMN_COUNT],
) -> Result<()>
Expand description
Render a table.
Writes a table containing data from iter
, an Iterator
over rows implementing IntoIterator
, which, in turn,
yields values that implement Display
, into the to
writer (which can be stdout
, a Vec<u8>
, etc.).
The width of each column is fixed (as specified by column_widths
).
(If the type you want to display does not implement Display
(or you want to use a different format
than the one provided by Display
), use write_table_with_fmt
instead.)
§Examples
let columns = ["x", "x²"];
let column_widths = [3, 4].map(|n| NonZeroUsize::new(n).expect("non zero"));
let data = [[1, 1], [2, 4], [3, 9], [4, 16]];
write_table(stdout.lock(), data.iter(), &columns, &column_widths)?;
╭───┬────╮
│ x │ x² │
├───┼────┤
│ 1 │ 1 │
│ 2 │ 4 │
│ 3 │ 9 │
│ 4 │ 16 │
╰───┴────╯
Non-trivial iterators are supported:
let columns = ["x", "x²"];
let column_widths = [3, 4].map(|n| NonZeroUsize::new(n).expect("non zero"));
let iter = (1..).take(4).map(|n| [n, n * n]);
write_table(stdout.lock(), iter, &columns, &column_widths)?;
╭───┬────╮
│ x │ x² │
├───┼────┤
│ 1 │ 1 │
│ 2 │ 4 │
│ 3 │ 9 │
│ 4 │ 16 │
╰───┴────╯
§Errors
If an I/O error is encountered while writing to the to
writer, that error will be returned.