pub fn write_table_with_fmt<Row, const COLUMN_COUNT: usize>(
to: impl Write,
iter: impl Iterator<Item = Row>,
formatters: &[impl Fn(&Row, &mut String) -> Result; COLUMN_COUNT],
column_names: &[&str; COLUMN_COUNT],
column_widths: &[NonZeroUsize; COLUMN_COUNT],
) -> Result<()>Expand description
Render a table using custom formatters.
Variant of write_table that converts values to text using the provided formatters instead of the Display
trait. Besides being able to use a different representation than the one provided by a type’s Display
implementation, it is also useful for displaying values that do not implement Display.
§Examples
use std::fmt::Write;
let addrs = [
Ipv4Addr::new(192, 168, 0, 1),
Ipv4Addr::new(1, 1, 1, 1),
Ipv4Addr::new(255, 127, 63, 31),
];
let column_names = ["Full address", "BE bits", "Private"];
let column_widths = [17, 12, 7].map(|n| NonZeroUsize::new(n).expect("non zero"));
let formatters: [fn(&Ipv4Addr, &mut String) -> std::fmt::Result; 3] = [
|addr, f| write!(f, "{}", addr),
|addr, f| write!(f, "0x{:x}", addr.to_bits().to_be()),
|addr, f| write!(f, "{}", if addr.is_private() { "yes" } else { "no" }),
];
write_table_with_fmt(stdout.lock(), addrs.iter().copied(), &formatters, &column_names, &column_widths)?;╭─────────────────┬────────────┬───────╮
│ Full address │ BE bits │Private│
├─────────────────┼────────────┼───────┤
│ 192.168.0.1 │ 0x100a8c0 │ yes │
│ 1.1.1.1 │ 0x1010101 │ no │
│ 255.127.63.31 │ 0x1f3f7fff │ no │
╰─────────────────┴────────────┴───────╯§Errors
If an I/O error is encountered while writing to the to writer, that error will be returned.