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.

Example

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'.

In this example, we defined a struct called Student with three fields.

Then, we created an instance of the Student struct named stud.

We then used the reflect.ValueOf() function to get the reflection value of the struct instance.

Then, we used the FieldByName() method to get the field by name.

The FieldByName() method returns a zero Value if the field is not found.

We can use the IsValid() method on the returned value to check if the field exists in the Struct.

If the field is valid, we print a message that the Struct has the field; otherwise, we print a message suggesting that the field is not present.

Leave a Comment