MCPcopy
hub / github.com/pterm/pterm / TableFromStructSlice

Function TableFromStructSlice

putils/tabledata-from-struct-slice.go:13–64  ·  view source on GitHub ↗

TableFromStructSlice accepts a customized table printer and and a slice of a struct. The table will be populated with the values of the structs. The header will be set to the structs field name. Use .WithHasHeader() to color the header. The function will return the populated pterm.TablePrinter.

(tablePrinter pterm.TablePrinter, structSlice any)

Source from the content-addressed store, hash-verified

11// Use .WithHasHeader() to color the header.
12// The function will return the populated pterm.TablePrinter.
13func TableFromStructSlice(tablePrinter pterm.TablePrinter, structSlice any) *pterm.TablePrinter {
14 to := reflect.TypeOf(structSlice)
15 if to.Kind() != reflect.Slice {
16 return &tablePrinter
17 }
18 el := to.Elem()
19
20 isPointer := false
21 if el.Kind() == reflect.Ptr {
22 el = el.Elem()
23 isPointer = true
24 }
25
26 if el.Kind() != reflect.Struct {
27 return &tablePrinter
28 }
29
30 numFields := el.NumField()
31 fieldNames := make([]string, numFields)
32
33 for i := 0; i < numFields; i++ {
34 fieldNames[i] = el.Field(i).Name
35 }
36
37 records := pterm.TableData{
38 fieldNames,
39 }
40
41 obj := reflect.ValueOf(structSlice)
42
43 items := make([]any, obj.Len())
44 for i := 0; i < obj.Len(); i++ {
45 if isPointer {
46 items[i] = obj.Index(i).Elem().Interface()
47 } else {
48 items[i] = obj.Index(i).Interface()
49 }
50 }
51
52 for _, v := range items {
53 item := reflect.ValueOf(v)
54 record := make([]string, numFields)
55 for i := 0; i < numFields; i++ {
56 fieldVal := item.Field(i).Interface()
57 record[i] = pterm.Sprintf("%v", fieldVal)
58 }
59 records = append(records, record)
60 }
61 tablePrinter.Data = records
62
63 return &tablePrinter
64}
65
66// DefaultTableFromStructSlice will be populate the pterm.DefaultTable with the values of the structs. The header will be set to the structs field name.
67// Use .WithHasHeader() to color the header.

Callers 1

Calls 1

SprintfFunction · 0.92

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…