Golang struct reflection

Suppose we want to know all possible information about the fields of the Go struct. We can get all this stuff using reflection. In this article you’ll find the answers to these questions:

  • 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

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()
}

That’s all.

Telegram channel

If you still have any questions, feel free to ask me in the comments under this article or write me at promark33@gmail.com.

If I saved your day, you can support me 🤝

Leave a Reply

Your email address will not be published. Required fields are marked *