Skip to content

Helper Functions API Reference

Utility functions for creating tables from structs, maps, and more.

Struct-Based Functions

FromStructs()

Creates a table from a slice of structs with automatic column detection.

go
func FromStructs[T any](title string, data []T) *Table

Type Parameters:

  • T: Any struct type

Parameters:

  • title (string): Window title
  • data ([]T): Slice of struct instances

Returns:

  • *Table: Configured table ready to show

Features:

  • Automatic column names from struct field names
  • Respects gotableview struct tags
  • Automatic type formatting
  • Skips unexported fields
  • Skips fields tagged with gotableview:"-"

Example:

go
type Person struct {
    Name   string  `gotableview:"Full Name"`
    Age    int     `gotableview:"Age"`
    Salary float64 `gotableview:"Annual Salary"`
}

people := []Person{
    {"Alice", 30, 75000.50},
    {"Bob", 25, 60000.00},
}

gotableview.FromStructs("People", people).Show()

Automatic Type Formatting:

  • int, int8, int16, int32, int64 → Integer string
  • uint, uint8, uint16, uint32, uint64 → Unsigned integer string
  • float32, float64 → Two decimal places (e.g., "3.14")
  • bool → "Yes" or "No"
  • time.Time → "2006-01-02 15:04:05"
  • nil pointers → Empty string
  • Other types → String representation via fmt.Sprintf("%v", value)

FromStructsPaginated()

Creates a paginated table from a slice of structs.

go
func FromStructsPaginated[T any](title string, data []T, pageSize int) *PaginatedTable

Type Parameters:

  • T: Any struct type

Parameters:

  • title (string): Window title
  • data ([]T): Slice of struct instances
  • pageSize (int): Rows per page

Returns:

  • *PaginatedTable: Configured paginated table

Example:

go
type LogEntry struct {
    ID      int       `gotableview:"#"`
    Time    time.Time `gotableview:"Timestamp"`
    Level   string    `gotableview:"Level"`
    Message string    `gotableview:"Message"`
}

logs := make([]LogEntry, 1000)
// ... populate logs ...

gotableview.FromStructsPaginated("Application Logs", logs, 100).
    SearchInColumns("Level", "Message").
    Show()

When to Use:

  • Dataset has 100+ items
  • Need search functionality
  • Want better performance with large data

Map-Based Functions

FromMaps()

Creates a table from a slice of maps.

go
func FromMaps(title string, data []map[string]any) *Table

Parameters:

  • title (string): Window title
  • data ([]map[string]any): Slice of maps with string keys

Returns:

  • *Table: Configured table

Features:

  • Detects columns from all map keys
  • Handles missing keys (shows as empty)
  • Column order may vary
  • Automatic type formatting

Example:

go
data := []map[string]any{
    {"Name": "Alice", "Age": 30, "City": "NYC"},
    {"Name": "Bob", "Age": 25, "City": "LA"},
    {"Name": "Carol", "City": "Chicago"},  // Missing "Age"
}

gotableview.FromMaps("People", data).Show()

Use Cases:

  • JSON data (after unmarshaling)
  • plyGO Select() results
  • Dynamic data structures
  • API responses

FromMapsPaginated()

Creates a paginated table from a slice of maps.

go
func FromMapsPaginated(title string, data []map[string]any, pageSize int) *PaginatedTable

Parameters:

  • title (string): Window title
  • data ([]map[string]any): Slice of maps
  • pageSize (int): Rows per page

Returns:

  • *PaginatedTable: Configured paginated table

Example:

go
// From plyGO Select()
result := plygo.From(employees).
    Select("Name", "Department", "Salary").
    Where("Salary").GreaterThan(70000.0).
    Collect()  // Returns []map[string]any

gotableview.FromMapsPaginated("High Earners", result, 50).
    WithSearch().
    Show()

Quick Display Functions

Show()

Quick helper to display a table without creating an instance.

go
func Show(title string, columns []string, rows [][]string)

Parameters:

  • title (string): Window title
  • columns ([]string): Column headers
  • rows ([][]string): Row data

Returns:

  • None (displays immediately)

Example:

go
columns := []string{"Name", "Age", "City"}
rows := [][]string{
    {"Alice", "30", "NYC"},
    {"Bob", "25", "LA"},
}

gotableview.Show("Quick Table", columns, rows)

When to Use:

  • Quick debugging
  • Simple one-off displays
  • Prototyping

ShowWithWidths()

Quick display with custom column widths.

go
func ShowWithWidths(title string, columns []string, widths []int, rows [][]string)

Parameters:

  • title (string): Window title
  • columns ([]string): Column headers
  • widths ([]int): Column widths in pixels
  • rows ([][]string): Row data

Returns:

  • None (displays immediately)

Example:

go
columns := []string{"ID", "Description", "Price"}
widths := []int{50, 300, 100}
rows := [][]string{
    {"1", "Long product description here", "$99.99"},
}

gotableview.ShowWithWidths("Products", columns, widths, rows)

Struct Tags

gotableview Tag

Control how struct fields appear in tables.

Syntax:

go
type MyStruct struct {
    Field string `gotableview:"value"`
}

Tag Values:

Custom Column Name

go
type Product struct {
    ID   int    `gotableview:"Product ID"`
    Name string `gotableview:"Product Name"`
}
// Columns: "Product ID", "Product Name"

Hide Field

go
type User struct {
    Name     string `gotableview:"Name"`
    Password string `gotableview:"-"`  // Hidden
    Email    string `gotableview:"Email"`
}
// Columns: "Name", "Email" (Password not shown)

No Tag (Use Field Name)

go
type Person struct {
    Name string  // Column: "Name"
    Age  int     // Column: "Age"
}

Type Formatting Details

formatValue()

Internal function that formats values (not directly callable).

Format Rules:

Strings

go
"Hello""Hello"

Integers

go
42"42"
-100"-100"

Floats

go
3.14159"3.14"
99.9"99.90"

Booleans

go
true"Yes"
false"No"

Time

go
time.Now() → "2024-01-15 14:30:45"

Pointers

go
var ptr *int = nil""
var ptr *int = &value → formatValue(*ptr)

Other Types

go
anyType → fmt.Sprintf("%v", anyType)

Complete Examples

Example 1: Struct with Tags

go
package main

import (
    "time"
    "github.com/mansoldof/goTableView"
)

type Employee struct {
    ID         int       `gotableview:"Employee #"`
    FirstName  string    `gotableview:"First Name"`
    LastName   string    `gotableview:"Last Name"`
    Email      string    `gotableview:"Email Address"`
    Department string    `gotableview:"Dept"`
    Salary     float64   `gotableview:"Annual Salary"`
    StartDate  time.Time `gotableview:"Start Date"`
    Active     bool      `gotableview:"Active"`
    SSN        string    `gotableview:"-"`  // Hidden
}

func main() {
    employees := []Employee{
        {1, "Alice", "Johnson", "alice@corp.com", "Engineering", 75000, time.Now(), true, "123-45-6789"},
        {2, "Bob", "Smith", "bob@corp.com", "Sales", 60000, time.Now(), true, "987-65-4321"},
    }
    
    gotableview.FromStructs("Employee Directory", employees).Show()
}

Example 2: Maps from JSON

go
package main

import (
    "encoding/json"
    "net/http"
    "github.com/mansoldof/goTableView"
)

func main() {
    resp, _ := http.Get("https://api.example.com/users")
    defer resp.Body.Close()
    
    var users []map[string]any
    json.NewDecoder(resp.Body).Decode(&users)
    
    gotableview.FromMapsPaginated("API Users", users, 50).
        WithSearch().
        Show()
}

Example 3: Mixed Types

go
package main

import (
    "time"
    "github.com/mansoldof/goTableView"
)

type Stats struct {
    Name      string    `gotableview:"Metric"`
    Value     float64   `gotableview:"Value"`
    Timestamp time.Time `gotableview:"Last Updated"`
    Enabled   bool      `gotableview:"Enabled"`
}

func main() {
    stats := []Stats{
        {"CPU Usage", 45.67, time.Now(), true},
        {"Memory", 78.23, time.Now(), true},
        {"Disk I/O", 12.45, time.Now(), false},
    }
    
    gotableview.FromStructs("System Stats", stats).Show()
}

Example 4: Pointers and Nil

go
package main

import "github.com/mansoldof/goTableView"

type OptionalData struct {
    Name  string   `gotableview:"Name"`
    Age   *int     `gotableview:"Age"`
    Score *float64 `gotableview:"Score"`
}

func main() {
    age1 := 30
    score1 := 95.5
    
    data := []OptionalData{
        {"Alice", &age1, &score1},
        {"Bob", nil, nil},  // nil pointers show as empty
    }
    
    gotableview.FromStructs("Optional Fields", data).Show()
}

Best Practices

1. Use FromStructs for Clean Code

go
// Instead of this ❌
table := gotableview.New("People")
table.Columns("Name", "Age", "Salary")
for _, p := range people {
    table.Row(p.Name, fmt.Sprintf("%d", p.Age), fmt.Sprintf("%.2f", p.Salary))
}
table.Show()

// Do this ✅
gotableview.FromStructs("People", people).Show()

2. Use Tags for User-Friendly Names

go
type Product struct {
    SKU   string `gotableview:"Product Code"`  // Better than "SKU"
    Desc  string `gotableview:"Description"`   // Better than "Desc"
    Price float64 `gotableview:"Price ($)"`    // Adds context
}

3. Hide Sensitive Data

go
type User struct {
    Name     string `gotableview:"Name"`
    Email    string `gotableview:"Email"`
    Password string `gotableview:"-"`        // Hidden
    APIKey   string `gotableview:"-"`        // Hidden
}

4. Choose Right Function

go
// For structs, use FromStructs
gotableview.FromStructs("Title", structSlice).Show()

// For maps (JSON, plyGO results), use FromMaps
gotableview.FromMaps("Title", mapSlice).Show()

// For large datasets, use paginated versions
gotableview.FromStructsPaginated("Title", data, 100).Show()
gotableview.FromMapsPaginated("Title", data, 100).Show()

Function Comparison

FunctionInput TypePaginationReturnsBest For
FromStructs[]struct*TableSmall struct datasets
FromStructsPaginated[]struct*PaginatedTableLarge struct datasets
FromMaps[]map[string]any*TableSmall map datasets
FromMapsPaginated[]map[string]any*PaginatedTableLarge map datasets
Show[][]stringvoidQuick debugging
ShowWithWidths[][]stringvoidQuick with custom widths

See Also

Released under the MIT License.