Dynamically Retrieving Keys and Values from Struct Property

Gists

This is a sample script for dynamically retrieving the keys and values from struct property using golang.

Sample script:

Go Playground

package main

import (
	"fmt"
	"reflect"
)

func main() {
	s := struct {
		key1 string
		key2 string
		key3 string
	}{"value1", "value2", "value3"}

	r := reflect.ValueOf(&s).Elem()
	rt := r.Type()
	for i := 0; i < rt.NumField(); i++ {
		field := rt.Field(i)
		rv := reflect.ValueOf(&s)
		value := reflect.Indirect(rv).FieldByName(field.Name)
		fmt.Println(field.Name, value.String())
	}
}

 Share!