Skip to content

Instantly share code, notes, and snippets.

@theverything
Created October 19, 2021 23:59
Show Gist options
  • Save theverything/439271149c5be3aa1dce2ebed35f64f6 to your computer and use it in GitHub Desktop.
Save theverything/439271149c5be3aa1dce2ebed35f64f6 to your computer and use it in GitHub Desktop.
Golang Key Value Table
package kvtable
import (
"fmt"
"strings"
)
type Row struct {
Key string
Value string
}
func Create(data []Row) string {
magic := 5
var keyPadding int
var valPadding int
for _, row := range data {
if len(row.Key) > keyPadding {
keyPadding = len(row.Key)
}
if len(row.Value) > valPadding {
valPadding = len(row.Value)
}
}
line := fmt.Sprintf("+%s+", strings.Repeat("-", magic+keyPadding+valPadding))
var table strings.Builder
fmt.Fprint(&table, line)
for _, row := range data {
fmt.Fprintf(&table, "\n| %-*s | %-*s |\n%s", keyPadding, row.Key, valPadding, row.Value, line)
}
return table.String()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment