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.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.