tabular

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 7, 2025 License: MIT Imports: 5 Imported by: 0

README

tabular

Go Reference

tabular is a small Go package for printing tabular text.

I originally wrote this package as an alternative to text/tabwriter because I needed to omit the trailing padding in each row that that package's algorithm creates. This resulting package is a little simpler than text/tabwriter and is better-suited to my typical needs. See the doc comments for more comparisons between tabular and text/tabwriter.

Documentation

Overview

Package tabular implements a simple tabular formatter for text.

The package is an alternative to text/tabwriter for some use cases. In comparison with text/tabwriter, this package:

  • Is oriented around rows and cells, not tab-delimited text
  • Inserts padding between cells, not after each cell
  • Does not count padding toward min-width
  • Does not insert any padding after the last cell of each row
  • Allows for per-cell right-alignment
  • Omits several lesser-used features of tabwriter
  • Attempts to guess the width of multibyte code points
  • Ignores ANSI CSI sequences

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Left

func Left(v any) any

Left marks a value passed to Buffer.AddRow for left alignment.

func Right(v any) any

Right marks a value passed to Buffer.AddRow for right alignment.

Types

type Buffer

type Buffer struct {
	// contains filtered or unexported fields
}

A Buffer stores rows of text and prints them as a table.

To calculate the width of a table cell, it strips out any ANSI CSI sequences from the text and then uses go-runewidth to guess the width of the resulting text.

Example
package main

import (
	"os"

	"github.com/cespare/tabular"
)

func main() {
	b := tabular.New(tabular.Options{Padding: 2, PadChar: ' ', AlignRight: true})
	b.AddRow("x", "x²", "x³")
	for _, x := range []float64{0, 4, 8, 12} {
		b.AddRow(x, x*x, x*x*x)
	}
	b.WriteTo(os.Stdout)

}
Output:

 x   x²    x³
 0    0     0
 4   16    64
 8   64   512
12  144  1728

func New

func New(opts Options) *Buffer

New constructs a Buffer with options.

func (*Buffer) AddRow

func (b *Buffer) AddRow(vs ...any)

AddRow adds a row of values to the buffer.

Each value is turned into a string using the same formatting as fmt.Sprint.

func (*Buffer) WriteTo

func (b *Buffer) WriteTo(w io.Writer) (int64, error)

WriteTo writes the buffered rows as a text table.

type Options

type Options struct {
	MinWidth   int  // Minimum cell width (not including padding).
	Padding    int  // Padding between each cell.
	PadChar    byte // The character to use for padding.
	AlignRight bool // Align cells to the right by default.
}

Options configure a Buffer.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL