Skip to content

Instantly share code, notes, and snippets.

@edr3x
Created October 21, 2024 15:18
Show Gist options
  • Save edr3x/8ec2472c08bc7093d93589a3ba44990b to your computer and use it in GitHub Desktop.
Save edr3x/8ec2472c08bc7093d93589a3ba44990b to your computer and use it in GitHub Desktop.
func PrintStructInTable(v interface{}) {
val := reflect.ValueOf(v)
typ := reflect.TypeOf(v)
// Ensure that the input is a struct
if typ.Kind() != reflect.Struct {
fmt.Println("Input is not a struct")
return
}
// Print table header
fmt.Printf("%-20s | %-20s\n", "Field", "Value")
fmt.Println(strings.Repeat("-", 43))
// Iterate over the struct fields
for i := 0; i < val.NumField(); i++ {
field := typ.Field(i)
value := val.Field(i)
// Format the field name and value
fieldName := field.Name
fieldValue := fmt.Sprintf("%v", value.Interface())
// Print each field and value in table format
fmt.Printf("%-20s | %-20s\n", fieldName, fieldValue)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment