printing fields of the structure with their names in golang
package main
import (
"fmt"
"reflect"
)
type Person struct {
Name string
Age int
Address string
}
func printFields(s interface{}) {
val := reflect.ValueOf(s)
typ := val.Type()
for i := 0; i < val.NumField(); i++ {
fieldName := typ.Field(i).Name
fieldValue := val.Field(i).Interface()
fmt.Printf("%s: %v\n", fieldName, fieldValue)
}
}
func main() {
person := Person{
Name: "John Doe",
Age: 30,
Address: "123 Main St",
}
printFields(person)
}