« Back to Index

Go: loop over struct fields

View original Gist on GitHub

Tags: #go #reflection

loop struct fields.go

package main

import (
	"fmt"
	"reflect"
)

type Student struct {
	Fname  string
	Lname  string
	City   string
	Mobile int64
}

func main() {
	s := Student{"Chetan", "Tulsyan", "Bangalore", 7777777777}
	v := reflect.ValueOf(s)
	typeOfS := v.Type()

	for i := 0; i < v.NumField(); i++ {
		fmt.Printf("Field: %s\tValue: %v\n", typeOfS.Field(i).Name, v.Field(i).Interface())
	}
}