Go struct reflection
What's inside this article
⌄
- Golang get struct field names
- Golang check struct field null by name
- Golang get struct field type by name
- Golang get struct field tag
- Golang check struct field empty
- Golang struct reflection
You can use this piece of code to get this information from the structure using reflection and print it in tabular form. This code also takes into account pointer types, and it finds the origin type:
package main
import (
"fmt"
"os"
"reflect"
"strconv"
"text/tabwriter"
)
func main() {
type Test struct {
Name string `db:"tag1"` // filled value
Surname *string `db:"tag2"` // pointer to non-empty string
Address string `db:"tag3"` // non-filled value (will be defaulted by empty string)
Zip *string `db:"tag4"` // non-filled pointer
Phone *string `db:"tag5"` // pointer to empty string
}
surname := "surname"
phone := ""
test := &Test{
Name: "name",
Surname: &surname,
Phone: &phone,
}
structRef := reflect.ValueOf(test).Elem()
structRefType := structRef.Type()
table := tabwriter.NewWriter(os.Stdout, 1, 1, 1, ' ', 0)
fmt.Fprintln(table, "field_name \tfield_type \tfield_tag \tis_empty_or_null")
for i := 0; i < structRef.NumField(); i++ {
fieldRefValue := structRef.Field(i)
fieldRefType := structRefType.Field(i)
isPointer := fieldRefValue.Kind() == reflect.Ptr
varName := fieldRefType.Name
varTag := string(fieldRefType.Tag.Get("db"))
varType := fieldRefType.Type
var varEmptyOrNull string
if isPointer {
varEmptyOrNull = strconv.FormatBool(fieldRefValue.IsNil() || fieldRefValue.Elem().IsZero())
} else {
varEmptyOrNull = strconv.FormatBool(fieldRefValue.IsZero())
}
fmt.Fprintf(table, "%v \t%v \t%v \t%v \n", varName, varType, varTag, varEmptyOrNull)
}
table.Flush()
}