Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Created June 25, 2019 05:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanaikech/9dc4718ac9fb2473ef029eb4dbda1b01 to your computer and use it in GitHub Desktop.
Save tanaikech/9dc4718ac9fb2473ef029eb4dbda1b01 to your computer and use it in GitHub Desktop.
Dynamically Retrieving Keys and Values from Struct Property

Dynamically Retrieving Keys and Values from Struct Property

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())
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment