The tw package defines core types, interfaces, constants, and utility functions for table formatting and configuration. It provides the foundational type system for the tablewriter library, including cell configuration, rendering contexts, border symbols, generic collections, and text manipulation utilities.
github.com/olekukonko/tablewriter/twimport "github.com/olekukonko/tablewriter/tw"The tw package serves as the core type system for tablewriter, providing:
The tw package is organized into several logical subsystems:
Interface for table rendering engines that output to an io.Writer.
type Renderer interface {
Start(w io.Writer) error
Header(headers [][]string, ctx Formatting)
Row(row []string, ctx Formatting)
Footer(footers [][]string, ctx Formatting)
Line(ctx Formatting)
Config() Rendition
Close() error
Logger(logger *ll.Logger)
}Methods:
Start(w io.Writer) error - Initialize renderer with output writerHeader(headers [][]string, ctx Formatting) - Render header section with formatting contextRow(row []string, ctx Formatting) - Render single data row with formatting contextFooter(footers [][]string, ctx Formatting) - Render footer section with formatting contextLine(ctx Formatting) - Render separator line based on formatting contextConfig() Rendition - Get current renderer configurationClose() error - Finalize rendering and cleanup resourcesLogger(logger *ll.Logger) - Set logger instance for rendererInterface for types that can update their rendition configuration dynamically.
type Renditioning interface {
Rendition(r Rendition)
}Methods:
Rendition(r Rendition) - Update rendition configurationInterface for table border symbol sets.
type Symbols interface {
Name() string
Center() string
Row() string
Column() string
TopLeft() string
TopMid() string
TopRight() string
MidLeft() string
MidRight() string
BottomLeft() string
BottomMid() string
BottomRight() string
HeaderLeft() string
HeaderMid() string
HeaderRight() string
}Methods:
Name() string - Style nameCenter() string - Junction symbol where lines crossRow() string - Horizontal line characterColumn() string - Vertical line characterTopLeft() string - Top-left corner symbolTopMid() string - Top junction (T pointing down)TopRight() string - Top-right corner symbolMidLeft() string - Left junction (T pointing right)MidRight() string - Right junction (T pointing left)BottomLeft() string - Bottom-left corner symbolBottomMid() string - Bottom junction (T pointing up)BottomRight() string - Bottom-right corner symbolHeaderLeft() string - Header left junction symbolHeaderMid() string - Header middle junction symbolHeaderRight() string - Header right junction symbolInterface for types that can format themselves into a string.
type Formatter interface {
Format() string
}Methods:
Format() string - Returns formatted string representationInterface combining io.Writer with total retrieval for counting operations (lines, bytes, etc.).
type Counter interface {
io.Writer
Total() int
}Methods:
Write(p []byte) (n int, err error) - io.Writer implementationTotal() int - Get total countDefines table section location (header, row, or footer).
type Position string
const (
Header Position = "header"
Row Position = "row"
Footer Position = "footer"
)
func (pos Position) Validate() errorConstants:
Header - Table header sectionRow - Table row section (data)Footer - Table footer sectionMethods:
Validate() error - Validates position is one of the allowed valuesText alignment within table cells.
type Align string
const (
AlignNone Align = "none"
AlignCenter Align = "center"
AlignRight Align = "right"
AlignLeft Align = "left"
AlignDefault Align = AlignLeft
Skip Align = ""
)
func (a Align) Validate() errorConstants:
AlignNone - No alignment appliedAlignCenter - Center-aligned textAlignRight - Right-aligned textAlignLeft - Left-aligned textAlignDefault - Default alignment (same as AlignLeft)Skip - Skip alignment for this columnMethods:
Validate() error - Validates alignment is one of the allowed valuesSlice of Align values with utility methods for managing column alignments.
type Alignment []Align
func (a Alignment) String() string
func (a Alignment) Add(aligns ...Align) Alignment
func (a Alignment) Set(col int, align Align) Alignment
func (a Alignment) Copy() AlignmentMethods:
String() string - String representation in format "0=left; 1=center; 2=right"Add(aligns ...Align) Alignment - Creates new Alignment with specified alignmentsSet(col int, align Align) Alignment - Sets alignment for specific column indexCopy() Alignment - Creates independent copy of alignmentRepresents on/off/unknown state for features and settings.
type State int
const (
Unknown State = 0
On State = 1
Off State = -1
)
func (o State) Enabled() bool
func (o State) Default() bool
func (o State) Disabled() bool
func (o State) Toggle() State
func (o State) Cond(c func() bool) bool
func (o State) Or(c State) State
func (o State) String() stringConstants:
Unknown - State is unknown/default (value: 0)On - State is enabled (value: 1)Off - State is disabled (value: -1)Methods:
Enabled() bool - Returns true if state is OnDefault() bool - Returns true if state is UnknownDisabled() bool - Returns true if state is OffToggle() State - Switches between On and OffCond(c func() bool) bool - Executes function if state is enabled, returns resultOr(c State) State - Returns this state if enabled, otherwise returns cString() string - Returns "on", "off", or "undefined"Hierarchical level in table structure (header, body, or footer).
type Level int
const (
LevelHeader Level = 0
LevelBody Level = 1
LevelFooter Level = 2
)
func (l Level) Validate() errorConstants:
LevelHeader - Header level (value: 0)LevelBody - Body/data level (value: 1)LevelFooter - Footer level (value: 2)Methods:
Validate() error - Validates level is one of the allowed valuesHorizontal position within table row (first, middle, or end).
type Location string
const (
LocationFirst Location = "first"
LocationMiddle Location = "middle"
LocationEnd Location = "end"
)
func (l Location) Validate() errorConstants:
LocationFirst - First position in rowLocationMiddle - Middle position in rowLocationEnd - End position in rowMethods:
Validate() error - Validates location is one of the allowed valuesTable caption with positioning and alignment.
type Caption struct {
Text string
Spot Spot
Align Align
Width int
}
func (c Caption) WithText(text string) Caption
func (c Caption) WithSpot(spot Spot) Caption
func (c Caption) WithAlign(align Align) Caption
func (c Caption) WithWidth(width int) CaptionFields:
Text string - Caption text contentSpot Spot - Caption position (top/bottom, left/center/right)Align Align - Text alignment within captionWidth int - Maximum width for captionMethods:
WithText(text string) Caption - Sets caption textWithSpot(spot Spot) Caption - Sets caption positionWithAlign(align Align) Caption - Sets caption alignmentWithWidth(width int) Caption - Sets caption maximum widthCaption position enumeration.
type Spot int
const (
SpotNone Spot = 0
SpotTopLeft Spot = 1
SpotTopCenter Spot = 2
SpotTopRight Spot = 3
SpotBottomLeft Spot = 4
SpotBottomCenter Spot = 5
SpotBottomRight Spot = 6
SpotLeftTop Spot = 7
SpotLeftCenter Spot = 8
SpotLeftBottom Spot = 9
SpotRightTop Spot = 10
SpotRightCenter Spot = 11
SpotRIghtBottom Spot = 12
)Constants:
SpotNone - No caption positionSpotTopLeft - Top-left positionSpotTopCenter - Top-center positionSpotTopRight - Top-right positionSpotBottomLeft - Bottom-left positionSpotBottomCenter - Bottom-center position (default)SpotBottomRight - Bottom-right positionSpotLeftTop - Left-top positionSpotLeftCenter - Left-center positionSpotLeftBottom - Left-bottom positionSpotRightTop - Right-top positionSpotRightCenter - Right-center positionSpotRIghtBottom - Right-bottom positionSection control settings for hiding/showing table sections.
type Control struct {
Hide State
}Fields:
Hide State - State controlling visibility of sectionCompact width optimization settings for merged cells.
type Compact struct {
Merge State
}Fields:
Merge State - Enables compact width calculation during cell mergingSettings for struct-based operations like automatic header extraction.
type Struct struct {
AutoHeader State
Tags []string
}Fields:
AutoHeader State - Automatically extract headers from struct field names when using Bulk with struct slicesTags []string - Priority-ordered list of struct tag keys to check for header names (defaults: ["json", "db"])Settings controlling table rendering behaviors.
type Behavior struct {
AutoHide State
TrimSpace State
TrimLine State
Header Control
Footer Control
Compact Compact
Structs Struct
}Fields:
AutoHide State - Auto-hide empty columns (ignored in streaming mode)TrimSpace State - Trim leading and trailing spaces from cell contentTrimLine State - Collapse empty visual lines within cellsHeader Control - Header section control settingsFooter Control - Footer section control settingsCompact Compact - Compact width optimization settingsStructs Struct - Struct processing settingsCell padding configuration for all four directions.
type Padding struct {
Left string
Right string
Top string
Bottom string
Overwrite bool
}
func (p Padding) Equals(padding Padding) bool
func (p Padding) Empty() bool
func (p Padding) Paddable() boolFields:
Left string - Left padding charactersRight string - Right padding charactersTop string - Top padding charactersBottom string - Bottom padding charactersOverwrite bool - Force exact usage, even when empty (overrides defaults)Methods:
Equals(padding Padding) bool - Checks equality with another PaddingEmpty() bool - Returns true if all padding strings are emptyPaddable() bool - Returns true if padding should override existing paddingDefault Counter implementation for counting newline characters.
type LineCounter struct {
// internal fields not exported
}
func (lc *LineCounter) Write(p []byte) (n int, err error)
func (lc *LineCounter) Total() intMethods:
Write(p []byte) (n int, err error) - Counts newlines in written bytesTotal() int - Returns total newline countFunction type for row-level cell content processing.
type Filter func([]string) []stringAccepts a slice of strings (representing a row) and returns a processed slice.
Cell formatting options.
type CellFormatting struct {
AutoWrap int
AutoFormat State
MergeMode int // Deprecated: use CellConfig.Merging.Mode
Alignment Align // Deprecated: use CellConfig.Alignment
}Fields:
AutoWrap int - Wrapping behavior (WrapNone, WrapNormal, WrapTruncate, WrapBreak)AutoFormat State - Enable automatic formatting (e.g., title case for headers)MergeMode int - Deprecated: Use CellConfig.Merging.Mode insteadAlignment Align - Deprecated: Use CellConfig.Alignment insteadCell merging configuration.
type CellMerging struct {
Mode int
ByColumnIndex Mapper[int, bool]
ByRowIndex Mapper[int, bool]
}Fields:
Mode int - Merge type bitmask (MergeNone, MergeVertical, MergeHorizontal, MergeBoth, MergeHierarchical)ByColumnIndex Mapper[int, bool] - Column indices to enable merging (nil/empty = all columns)ByRowIndex Mapper[int, bool] - Row indices to enable merging (reserved for future use)Cell padding settings with global and per-column configuration.
type CellPadding struct {
Global Padding
PerColumn []Padding
}Fields:
Global Padding - Default padding applied to all cellsPerColumn []Padding - Column-specific padding overridesCell filtering functions for processing content.
type CellFilter struct {
Global func([]string) []string
PerColumn []func(string) string
}Fields:
Global func([]string) []string - Processes entire row as slicePerColumn []func(string) string - Processes individual cells by columnCell callback functions (placeholder for future functionality).
type CellCallbacks struct {
Global func()
PerColumn []func()
}Fields:
Global func() - Global callback applied to all cellsPerColumn []func() - Column-specific callbacksCell alignment settings with global and per-column configuration.
type CellAlignment struct {
Global Align
PerColumn []Align
}Fields:
Global Align - Default alignment for all cellsPerColumn []Align - Column-specific alignment overridesComplete cell configuration combining all cell options.
type CellConfig struct {
Formatting CellFormatting
Padding CellPadding
Callbacks CellCallbacks
Filter CellFilter
Alignment CellAlignment
ColMaxWidths CellWidth
Merging CellMerging
ColumnAligns []Align // Deprecated: use Alignment.PerColumn
}Fields:
Formatting CellFormatting - Cell formatting optionsPadding CellPadding - Padding configurationCallbacks CellCallbacks - Callback functionsFilter CellFilter - Filter functions for content processingAlignment CellAlignment - Alignment settingsColMaxWidths CellWidth - Maximum width constraintsMerging CellMerging - Merge configurationColumnAligns []Align - Deprecated: Use Alignment.PerColumn insteadWidth constraints for cells and columns.
type CellWidth struct {
Global int
PerColumn Mapper[int, int]
}
func (c CellWidth) Constrained() boolFields:
Global int - Global maximum width for all cellsPerColumn Mapper[int, int] - Column-specific width constraintsMethods:
Constrained() bool - Returns true if any width constraints are setRenderer configuration.
type Rendition struct {
Borders Border
Symbols Symbols
Settings Settings
Streaming bool
}Fields:
Borders Border - Border visibility settingsSymbols Symbols - Border symbol setSettings Settings - Rendering behavior settingsStreaming bool - Streaming mode flagComplete formatting context for row rendering.
type Formatting struct {
Row RowContext
Level Level
HasFooter bool
IsSubRow bool
NormalizedWidths Mapper[int, int]
}Fields:
Row RowContext - Row configuration and stateLevel Level - Hierarchical level (Header/Body/Footer)HasFooter bool - Indicates if table includes footer sectionIsSubRow bool - Marks this as continuation line in multi-line rowsNormalizedWidths Mapper[int, int] - Calculated column widthsIndividual cell properties and state.
type CellContext struct {
Data string
Align Align
Padding Padding
Width int
Merge MergeState
}Fields:
Data string - Cell content to displayAlign Align - Text alignment within cellPadding Padding - Padding characters surrounding contentWidth int - Suggested display widthMerge MergeState - Cell spanning detailsCell merge state across all directions.
type MergeState struct {
Vertical MergeStateOption
Horizontal MergeStateOption
Hierarchical MergeStateOption
}Fields:
Vertical MergeStateOption - Vertical merge state (across rows)Horizontal MergeStateOption - Horizontal merge state (across columns)Hierarchical MergeStateOption - Hierarchical merge state (nested)Merge attributes for specific direction.
type MergeStateOption struct {
Present bool
Span int
Start bool
End bool
}Fields:
Present bool - True if merge is active in this directionSpan int - Number of cells this merge spansStart bool - True if this cell is merge starting pointEnd bool - True if this cell is merge ending pointRow layout properties and relationships.
type RowContext struct {
Position Position
Location Location
Current map[int]CellContext
Previous map[int]CellContext
Next map[int]CellContext
Widths Mapper[int, int]
ColMaxWidths CellWidth
}
func (r RowContext) GetCell(col int) CellContextFields:
Position Position - Table section (Header/Row/Footer)Location Location - Boundary position (First/Middle/End)Current map[int]CellContext - Cells in current row by column indexPrevious map[int]CellContext - Cells from previous row (for merge detection)Next map[int]CellContext - Cells from next row (for merge detection)Widths Mapper[int, int] - Computed widths for each columnColMaxWidths CellWidth - Maximum allowed width per columnMethods:
GetCell(col int) CellContext - Gets cell by column indexSeparator visibility settings.
type Separators struct {
ShowHeader State
ShowFooter State
BetweenRows State
BetweenColumns State
}Fields:
ShowHeader State - Show header separator lineShowFooter State - Show footer separator lineBetweenRows State - Show separators between rowsBetweenColumns State - Show separators between columnsTable boundary line settings.
type Lines struct {
ShowTop State
ShowBottom State
ShowHeaderLine State
ShowFooterLine State
}Fields:
ShowTop State - Show top border lineShowBottom State - Show bottom border lineShowHeaderLine State - Show header separator lineShowFooterLine State - Show footer separator lineRendering behavior configuration.
type Settings struct {
Separators Separators
Lines Lines
CompactMode State
}Fields:
Separators Separators - Separator visibility settingsLines Lines - Line visibility settingsCompactMode State - Compact rendering mode (reserved for future use)Border visibility states.
type Border struct {
Left State
Right State
Top State
Bottom State
Overwrite bool
}Fields:
Left State - Left border visibilityRight State - Right border visibilityTop State - Top border visibilityBottom State - Bottom border visibilityOverwrite bool - Force exact usage (override defaults)Streaming mode configuration.
type StreamConfig struct {
Enable bool
StrictColumns bool
Widths CellWidth // Deprecated: use top-level Config.Widths
}Fields:
Enable bool - Enable streaming modeStrictColumns bool - Return error if row column count doesn't match (default: false)Widths CellWidth - Deprecated: Use top-level Config.Widths insteadBorder styling enumeration with 44 predefined styles.
type BorderStyle int
const (
StyleNone BorderStyle = 0
StyleASCII BorderStyle = 1
StyleLight BorderStyle = 2
StyleHeavy BorderStyle = 3
StyleDouble BorderStyle = 4
StyleDoubleLong BorderStyle = 5
StyleLightHeavy BorderStyle = 6
StyleHeavyLight BorderStyle = 7
StyleLightDouble BorderStyle = 8
StyleDoubleLight BorderStyle = 9
StyleRounded BorderStyle = 10
StyleMarkdown BorderStyle = 11
StyleGraphical BorderStyle = 12
StyleMerger BorderStyle = 13
StyleDefault BorderStyle = 14
StyleDotted BorderStyle = 15
StyleArrow BorderStyle = 16
StyleStarry BorderStyle = 17
StyleHearts BorderStyle = 18
StyleCircuit BorderStyle = 19
StyleNature BorderStyle = 20
StyleArtistic BorderStyle = 21
Style8Bit BorderStyle = 22
StyleChaos BorderStyle = 23
StyleDots BorderStyle = 24
StyleBlocks BorderStyle = 25
StyleZen BorderStyle = 26
StyleVintage BorderStyle = 27
StyleSketch BorderStyle = 28
StyleArrowDouble BorderStyle = 29
StyleCelestial BorderStyle = 30
StyleCyber BorderStyle = 31
StyleRunic BorderStyle = 32
StyleIndustrial BorderStyle = 33
StyleInk BorderStyle = 34
StyleArcade BorderStyle = 35
StyleBlossom BorderStyle = 36
StyleFrosted BorderStyle = 37
StyleMosaic BorderStyle = 38
StyleUFO BorderStyle = 39
StyleSteampunk BorderStyle = 40
StyleGalaxy BorderStyle = 41
StyleJazz BorderStyle = 42
StylePuzzle BorderStyle = 43
StyleHypno BorderStyle = 44
)
func (s BorderStyle) String() stringConstants: 44 border style constants from StyleNone (0) to StyleHypno (44)
Methods:
String() string - Returns style name (e.g., "Light", "Heavy", "Rounded")Style name string type.
type StyleName string
const (
StyleNameNothing StyleName = "nothing"
StyleNameASCII StyleName = "ascii"
StyleNameLight StyleName = "light"
StyleNameHeavy StyleName = "heavy"
StyleNameDouble StyleName = "double"
StyleNameDoubleLong StyleName = "doublelong"
StyleNameLightHeavy StyleName = "lightheavy"
StyleNameHeavyLight StyleName = "heavylight"
StyleNameLightDouble StyleName = "lightdouble"
StyleNameDoubleLight StyleName = "doublelight"
StyleNameRounded StyleName = "rounded"
StyleNameMarkdown StyleName = "markdown"
StyleNameGraphical StyleName = "graphical"
StyleNameMerger StyleName = "merger"
StyleNameDotted StyleName = "dotted"
StyleNameArrow StyleName = "arrow"
StyleNameStarry StyleName = "starry"
StyleNameHearts StyleName = "hearts"
StyleNameCircuit StyleName = "circuit"
StyleNameNature StyleName = "nature"
StyleNameArtistic StyleName = "artistic"
StyleName8Bit StyleName = "8bit"
StyleNameChaos StyleName = "chaos"
StyleNameDots StyleName = "dots"
StyleNameBlocks StyleName = "blocks"
StyleNameZen StyleName = "zen"
StyleNameVintage StyleName = "vintage"
StyleNameSketch StyleName = "sketch"
StyleNameArrowDouble StyleName = "arrowdouble"
StyleNameCelestial StyleName = "celestial"
StyleNameCyber StyleName = "cyber"
StyleNameRunic StyleName = "runic"
StyleNameIndustrial StyleName = "industrial"
StyleNameInk StyleName = "ink"
StyleNameArcade StyleName = "arcade"
StyleNameBlossom StyleName = "blossom"
StyleNameFrosted StyleName = "frosted"
StyleNameMosaic StyleName = "mosaic"
StyleNameUFO StyleName = "ufo"
StyleNameSteampunk StyleName = "steampunk"
StyleNameGalaxy StyleName = "galaxy"
StyleNameJazz StyleName = "jazz"
StyleNamePuzzle StyleName = "puzzle"
StyleNameHypno StyleName = "hypno"
)
func (s StyleName) String() stringConstants: 44+ style name constants matching BorderStyle values
Methods:
String() string - Returns style name as stringCustomizable border style implementation with builder pattern.
type SymbolCustom struct {
// internal fields not exported
}
func NewSymbolCustom(name string) *SymbolCustom
func (c *SymbolCustom) Name() string
func (c *SymbolCustom) Center() string
func (c *SymbolCustom) Row() string
func (c *SymbolCustom) Column() string
func (c *SymbolCustom) TopLeft() string
func (c *SymbolCustom) TopMid() string
func (c *SymbolCustom) TopRight() string
func (c *SymbolCustom) MidLeft() string
func (c *SymbolCustom) MidRight() string
func (c *SymbolCustom) BottomLeft() string
func (c *SymbolCustom) BottomMid() string
func (c *SymbolCustom) BottomRight() string
func (c *SymbolCustom) HeaderLeft() string
func (c *SymbolCustom) HeaderMid() string
func (c *SymbolCustom) HeaderRight() string
func (c *SymbolCustom) WithCenter(s string) *SymbolCustom
func (c *SymbolCustom) WithRow(s string) *SymbolCustom
func (c *SymbolCustom) WithColumn(s string) *SymbolCustom
func (c *SymbolCustom) WithTopLeft(s string) *SymbolCustom
func (c *SymbolCustom) WithTopMid(s string) *SymbolCustom
func (c *SymbolCustom) WithTopRight(s string) *SymbolCustom
func (c *SymbolCustom) WithMidLeft(s string) *SymbolCustom
func (c *SymbolCustom) WithMidRight(s string) *SymbolCustom
func (c *SymbolCustom) WithBottomLeft(s string) *SymbolCustom
func (c *SymbolCustom) WithBottomMid(s string) *SymbolCustom
func (c *SymbolCustom) WithBottomRight(s string) *SymbolCustom
func (c *SymbolCustom) WithHeaderLeft(s string) *SymbolCustom
func (c *SymbolCustom) WithHeaderMid(s string) *SymbolCustom
func (c *SymbolCustom) WithHeaderRight(s string) *SymbolCustom
func (s *SymbolCustom) Preview() stringConstructor:
NewSymbolCustom(name string) *SymbolCustom - Creates customizable border styleMethods:
With* methods for setting each symbol (return *SymbolCustom for chaining)Preview() string - Renders small sample table to visualize border styleUsage Example:
custom := tw.NewSymbolCustom("MyStyle").
WithRow("=").
WithColumn("|").
WithCenter("+").
WithTopLeft("*").
WithTopRight("*")
// Preview the style
fmt.Println(custom.Preview())Border symbols with corners array representation (used by predefined styles).
type Glyphs struct {
// internal fields not exported
}
func (s *Glyphs) Name() string
func (s *Glyphs) Center() string
func (s *Glyphs) Row() string
func (s *Glyphs) Column() string
func (s *Glyphs) TopLeft() string
func (s *Glyphs) TopMid() string
func (s *Glyphs) TopRight() string
func (s *Glyphs) MidLeft() string
func (s *Glyphs) MidRight() string
func (s *Glyphs) BottomLeft() string
func (s *Glyphs) BottomMid() string
func (s *Glyphs) BottomRight() string
func (s *Glyphs) HeaderLeft() string
func (s *Glyphs) HeaderMid() string
func (s *Glyphs) HeaderRight() string
func (s *Glyphs) Preview() stringMethods:
Preview() string - Renders small sample table to visualize border styleGeneric map type with rich utility methods.
type Mapper[K comparable, V any] map[K]V
func NewMapper[K comparable, V any]() Mapper[K, V]
func (m Mapper[K, V]) Get(key K) V
func (m Mapper[K, V]) OK(key K) (V, bool)
func (m Mapper[K, V]) Set(key K, value V) Mapper[K, V]
func (m Mapper[K, V]) Delete(key K) Mapper[K, V]
func (m Mapper[K, V]) Has(key K) bool
func (m Mapper[K, V]) Len() int
func (m Mapper[K, V]) Keys() []K
func (m Mapper[K, V]) Clear()
func (m Mapper[K, V]) Values() []V
func (m Mapper[K, V]) Each(fn func(K, V))
func (m Mapper[K, V]) Filter(fn func(K, V) bool) Mapper[K, V]
func (m Mapper[K, V]) MapValues(fn func(V) V) Mapper[K, V]
func (m Mapper[K, V]) Clone() Mapper[K, V]
func (m Mapper[K, V]) Slicer() Slicer[KeyValuePair[K, V]]
func (m Mapper[K, V]) SortedKeys() []KConstructor:
NewMapper[K comparable, V any]() Mapper[K, V] - Creates new initialized MapperMethods:
Get(key K) V - Gets value by key (returns zero value if not found)OK(key K) (V, bool) - Gets value with existence checkSet(key K, value V) Mapper[K, V] - Sets value for keyDelete(key K) Mapper[K, V] - Removes keyHas(key K) bool - Checks if key existsLen() int - Returns number of entriesKeys() []K - Returns slice of all keysClear() - Removes all entriesValues() []V - Returns slice of all valuesEach(fn func(K, V)) - Iterates over entriesFilter(fn func(K, V) bool) Mapper[K, V] - Returns new Mapper with filtered entriesMapValues(fn func(V) V) Mapper[K, V] - Returns new Mapper with transformed valuesClone() Mapper[K, V] - Creates shallow copySlicer() Slicer[KeyValuePair[K, V]] - Converts to Slicer of key-value pairsSortedKeys() []K - Returns sorted keys (supports int, float, string types)Usage Example:
// Create a Mapper of column widths
widths := tw.NewMapper[int, int]()
widths.Set(0, 20).Set(1, 30).Set(2, 15)
// Iterate over widths
widths.Each(func(col int, width int) {
fmt.Printf("Column %d: %d\n", col, width)
})
// Filter widths > 15
wide := widths.Filter(func(col int, width int) bool {
return width > 15
})Key-value pair for Mapper operations.
type KeyValuePair[K comparable, V any] struct {
Key K
Value V
}Fields:
Key K - Key of the pairValue V - Value of the pairGeneric slice type with rich utility methods.
type Slicer[T any] []T
func NewSlicer[T any]() Slicer[T]
func (s Slicer[T]) Get(index int) T
func (s Slicer[T]) GetOK(index int) (T, bool)
func (s Slicer[T]) Append(elements ...T) Slicer[T]
func (s Slicer[T]) Prepend(elements ...T) Slicer[T]
func (s Slicer[T]) Len() int
func (s Slicer[T]) IsEmpty() bool
func (s Slicer[T]) Has(index int) bool
func (s Slicer[T]) First() T
func (s Slicer[T]) Last() T
func (s Slicer[T]) Each(fn func(T))
func (s Slicer[T]) Filter(fn func(T) bool) Slicer[T]
func (s Slicer[T]) Map(fn func(T) T) Slicer[T]
func (s Slicer[T]) Contains(fn func(T) bool) bool
func (s Slicer[T]) Find(fn func(T) bool) (T, bool)
func (s Slicer[T]) Clone() Slicer[T]Constructor:
NewSlicer[T any]() Slicer[T] - Creates new initialized SlicerMethods:
Get(index int) T - Gets element by index (returns zero value if out of bounds)GetOK(index int) (T, bool) - Gets element with bounds checkAppend(elements ...T) Slicer[T] - Appends elementsPrepend(elements ...T) Slicer[T] - Prepends elementsLen() int - Returns lengthIsEmpty() bool - Checks if emptyHas(index int) bool - Checks if index existsFirst() T - Gets first elementLast() T - Gets last elementEach(fn func(T)) - Iterates over elementsFilter(fn func(T) bool) Slicer[T] - Returns new Slicer with filtered elementsMap(fn func(T) T) Slicer[T] - Returns new Slicer with transformed elementsContains(fn func(T) bool) bool - Checks if any element satisfies predicateFind(fn func(T) bool) (T, bool) - Finds first element matching predicateClone() Slicer[T] - Creates shallow copyUsage Example:
// Create a Slicer of alignments
aligns := tw.NewSlicer[tw.Align]()
aligns = aligns.Append(tw.AlignLeft, tw.AlignCenter, tw.AlignRight)
// Filter to only center-aligned
centered := aligns.Filter(func(a tw.Align) bool {
return a == tw.AlignCenter
})const (
Pending = 0
Fail = -1
Success = 1
)Pending - Unknown/default state (value: 0)Fail - Operation failed / feature disabled (value: -1)Success - Operation succeeded / feature enabled (value: 1)const (
MinimumColumnWidth = 8
)MinimumColumnWidth - Minimum column width in charactersconst (
DefaultCacheStringCapacity = 10 * 1024
)DefaultCacheStringCapacity - Default string cache capacity (10 KB)const (
Empty = ""
Skip = ""
Space = " "
NewLine = "\n"
Column = ":"
Dash = "-"
)Empty - Empty stringSkip - Skip/ignore markerSpace - Single space characterNewLine - Line break characterColumn - Column separator characterDash - Dash characterconst (
SectionHeader = "header"
SectionRow = "row"
SectionFooter = "footer"
)SectionHeader - Header section nameSectionRow - Row section nameSectionFooter - Footer section nameconst (
WrapNone = 0
WrapNormal = 1
WrapTruncate = 2
WrapBreak = 3
)WrapNone - No wrappingWrapNormal - Standard word wrappingWrapTruncate - Truncate with ellipsisWrapBreak - Break long words to fitconst (
MergeNone = 0
MergeVertical = 1
MergeHorizontal = 2
MergeBoth = 3
MergeHierarchical = 4
)MergeNone - No mergingMergeVertical - Merge vertically identical cellsMergeHorizontal - Merge horizontally identical cellsMergeBoth - Merge both directionsMergeHierarchical - Hierarchical mergingconst (
CharEllipsis = "…"
CharBreak = "↩"
)CharEllipsis - Ellipsis character for truncationCharBreak - Break character for wrappingvar (
PaddingNone = Padding{Left: "", Right: "", Top: "", Bottom: "", Overwrite: true}
PaddingDefault = Padding{Left: " ", Right: " ", Overwrite: true}
BorderNone = Border{Left: Off, Right: Off, Top: Off, Bottom: Off}
LinesNone = Lines{ShowTop: Off, ShowBottom: Off, ShowHeaderLine: Off, ShowFooterLine: Off}
SeparatorsNone = Separators{ShowHeader: Off, ShowFooter: Off, BetweenRows: Off, BetweenColumns: Off}
)PaddingNone - Explicitly empty padding (no spacing on any side)PaddingDefault - Standard single-space padding on left/rightBorderNone - All borders disabledLinesNone - All lines disabledSeparatorsNone - All separators disabledvar Styles = map[BorderStyle]StyleName{ /* 44 style mappings */ }Maps BorderStyle constants to StyleName strings. Contains all 44 border style mappings.
func NewMapper[K comparable, V any]() Mapper[K, V]Creates new initialized Mapper with specified key and value types.
func NewBoolMapper[K comparable](keys ...K) Mapper[K, bool]Creates Mapper with boolean values set to true for given keys.
func NewIntMapper[K comparable](keys ...K) Mapper[K, int]Creates Mapper with integer values (keys as indices, all values initialized to 0).
func NewIdentityMapper[K comparable](keys ...K) Mapper[K, K]Creates Mapper with keys as values (identity mapping).
func NewSlicer[T any]() Slicer[T]Creates new initialized Slicer with specified element type.
func SlicerToMapper[K comparable, V any](s Slicer[KeyValuePair[K, V]]) Mapper[K, V]Converts Slicer of KeyValuePair to Mapper.
func NewSymbols(style BorderStyle) SymbolsCreates Symbols instance with specified predefined border style.
Parameters:
style BorderStyle - One of the 44 predefined border style constantsReturns: Symbols implementation for that style
Example:
symbols := tw.NewSymbols(tw.StyleRounded)
fmt.Println(symbols.TopLeft()) // "╭"func NewSymbolCustom(name string) *SymbolCustomCreates customizable border style with given name for fluent configuration.
Parameters:
name string - Custom style nameReturns: SymbolCustom instance for customization
Example:
custom := tw.NewSymbolCustom("MyStyle").
WithRow("-").
WithColumn("|").
WithCenter("+")func Title(name string) stringNormalizes and uppercases label for headers. Splits camelCase, converts underscores to spaces, and uppercases the result.
Parameters:
name string - Input label (may be camelCase, snake_case, etc.)Returns: Formatted uppercase header string
Example:
tw.Title("userName") // "USER NAME"
tw.Title("user_name") // "USER NAME"
tw.Title("first.last") // "FIRST LAST"func SplitCamelCase(src string) []stringSplits camelCase, PascalCase, or snake_case string into separate words.
Parameters:
src string - Input stringReturns: Slice of words
Example:
tw.SplitCamelCase("userName") // ["user", "Name"]
tw.SplitCamelCase("HTTPResponse") // ["HTTP", "Response"]
tw.SplitCamelCase("user_name") // ["user", "name"]func PadCenter(s, pad string, width int) stringCenters string within specified width using padding characters.
Parameters:
s string - Input stringpad string - Padding character(s)width int - Target widthReturns: Centered and padded string
func PadRight(s, pad string, width int) stringLeft-aligns string, padding on right side to reach target width.
Parameters:
s string - Input stringpad string - Padding character(s)width int - Target widthReturns: Left-aligned padded string
func PadLeft(s, pad string, width int) stringRight-aligns string, padding on left side to reach target width.
Parameters:
s string - Input stringpad string - Padding character(s)width int - Target widthReturns: Right-aligned padded string
func Pad(s, padChar string, totalWidth int, alignment Align) stringAligns string with padding based on alignment direction. Truncates if string exceeds width.
Parameters:
s string - Input stringpadChar string - Padding character(s)totalWidth int - Target widthalignment Align - Alignment direction (AlignLeft, AlignRight, AlignCenter)Returns: Aligned and padded (or truncated) string
func IsIsNumericOrSpace(r rune) boolChecks if rune is digit (0-9) or space character.
Parameters:
r rune - Rune to checkReturns: true if numeric or space
func IsNumeric(s string) boolChecks if string represents valid integer or floating-point number.
Parameters:
s string - String to checkReturns: true if valid number
func Or(cond bool, valid, inValid string) stringTernary-like string operation: returns valid if condition is true, else inValid.
Parameters:
cond bool - Conditionvalid string - Return if trueinValid string - Return if falseReturns: Selected string
func Max(a, b int) intReturns greater of two integers.
func Min(a, b int) intReturns smaller of two integers.
func BreakPoint(s string, limit int) intFinds rune index where display width first exceeds limit. Used for text wrapping.
Parameters:
s string - Input stringlimit int - Width limitReturns: Number of runes that fit within limit
func MakeAlign(l int, align Align) AlignmentCreates Alignment slice of length l filled with specified alignment.
Parameters:
l int - Length of alignment slicealign Align - Alignment to fill withReturns: Alignment slice
Example:
// Create alignment for 3 columns, all center-aligned
align := tw.MakeAlign(3, tw.AlignCenter)
// align == Alignment{AlignCenter, AlignCenter, AlignCenter}All types listed in the sections above are exported from the tw package. Key type categories: