WriteTable aligned columns with tabwriter

Go
package table

import (
    "fmt"
    "io"
    "strings"
    "text/tabwriter"
)

// WriteTable renders headers and rows as aligned plain-text columns using
// tabwriter, and rejects rows whose cell count differs from the header.
func WriteTable(w io.Writer, headers []string, rows [][]string) error {
    if len(headers) == 0 {
        return fmt.Errorf("table: no headers")
    }
    tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
    fmt.Fprintln(tw, strings.Join(headers, "\t"))
    rule := make([]string, len(headers))
    for i := range rule {
        rule[i] = strings.Repeat("-", len(headers[i]))
    }
    fmt.Fprintln(tw, strings.Join(rule, "\t"))
    for n, row := range rows {
        if len(row) != len(headers) {
            return fmt.Errorf("row %d: want %d cells, got %d", n, len(headers), len(row))
        }
        fmt.Fprintln(tw, strings.Join(row, "\t"))
    }
    return tw.Flush()
}