How to Check If Struct has Field in Golang

To check If Struct has a Field in Golang, you can “use the combination of the valueOf() and FieldByName() functions.”

The reflect.ValueOf() function takes an interface value as an argument and returns a reflect.Value represents the concrete value stored in the interface.

The FieldByName() is a method of the reflect.Value type that takes a string representing the field name as an argument and returns the reflect.Value of the struct field with the specified name.

package main

import (
  "fmt"
  "reflect"
)

type Student struct {
  Name string
  Age int
  Address string
}

func main() {
  stud := Student{Name: "John Doe", Age: 30, Address: "123 Main St"}

  fieldName := "Age"
  value := reflect.ValueOf(stud)
  field := value.FieldByName(fieldName)

  if field.IsValid() {
    fmt.Printf("The struct has the field '%s'.\n", fieldName)
  } else {
    fmt.Printf("The struct does not have the field '%s'.\n", fieldName)
  }
}

Output

The struct has the field 'Age'.

Summary

Key Point Description
Struct Definition MainStruct with fields Name and Age
Function HasField(st interface{}, name string) bool
Purpose Checks if a struct (or pointer to a struct) has a particular field
Key Methods reflect.ValueOf(st), val.FieldByName(name), field.IsValid()
Usage Example HasField(s, "Name") returns true
Performance Note The reflect package can be slow due to runtime reflection. Use cautiously in performance-critical paths.

That’s it!

2 thoughts on “How to Check If Struct has Field in Golang”

Comments are closed.