How to Iterate the Fields of a Struct in Go

To iterate the fields of a struct in Golang, you can use the reflect package’s “ValueOf()” function to iterate over the fields of a struct.

Example

package main

import (
  "fmt"
  "reflect"
)

type Student struct {
  Name string
  Rollno int
  City string
}

func iterateStructFields(input interface{}) {
  value := reflect.ValueOf(input)
  numFields := value.NumField()

  fmt.Printf("Number of fields: %d\n", numFields)

  structType := value.Type()

  for i := 0; i < numFields; i++ {
    field := structType.Field(i)
    fieldValue := value.Field(i)

    fmt.Printf("Field %d: %s (%s) = %v\n", i+1, field.Name, field.Type, fieldValue)
 }
}

func main() {
 student := Student{
 Name: "Krunal",
 Rollno: 30,
 City: "Rajkot",
 }

 iterateStructFields(student)
}

Output

Number of fields: 3

Field 1: Name (string) = Krunal
Field 2: Rollno (int) = 30
Field 3: City (string) = Rajkot

In this code example, we defined a Student struct with three fields: Name, Rollno, and City.

In the next step, we created a Student instance and passed it to the iterateStructFields() function.

Inside the function, we used the reflect package to iterate over the fields of the struct and printed their names, types, and values.

Note that using the reflect package might have some performance implications. Therefore, it’s generally recommended to avoid reflection when possible, but the reflect package is the way to go when you must iterate over struct fields generically.