Skip to content

Instantly share code, notes, and snippets.

Last active June 24, 2023 18:24
Star You must be signed in to star a gist
What would you like to do?
Golang Reflection Example
package main
import (
type Foo struct {
FirstName string `tag_name:"tag 1"`
LastName string `tag_name:"tag 2"`
Age int `tag_name:"tag 3"`
func (f *Foo) reflect() {
val := reflect.ValueOf(f).Elem()
for i := 0; i < val.NumField(); i++ {
valueField := val.Field(i)
typeField := val.Type().Field(i)
tag := typeField.Tag
fmt.Printf("Field Name: %s,\t Field Value: %v,\t Tag Value: %s\n", typeField.Name, valueField.Interface(), tag.Get("tag_name"))
func main() {
f := &Foo{
FirstName: "Drew",
LastName: "Olson",
Age: 30,
Copy link

himekami commented Mar 4, 2014

this is a good example for me.
thank you.

Copy link


Copy link

doojin commented Jun 3, 2014

Thank you very much!
Just helped me.

Copy link

lenw commented Aug 28, 2014

Copy link

Thanks very much for this! Very helpful.

Copy link

0proto commented Aug 28, 2015

Nice snippet, thanks!

Copy link

ulranh commented Aug 28, 2015

Thank you very much! Just needed it.

Copy link

danmondy commented Sep 1, 2015

Does the reflection logic change if foo is passed in as an empty interface? interface{}?

Copy link


Copy link

Thank you! 👍

Copy link

thanks to the author,A good example!

Copy link

sdtsui commented Sep 22, 2016

thanks @drewolson, and @lenw for posting the snippet

Copy link

rmasci commented Feb 14, 2017

yeah this helped me a lot!!

Copy link

This is a good example. Thanks.

Copy link

good example. tks

Copy link

This is a good example. It helped me!

Copy link

So nice example. Hah, solve my problem perfectly

Copy link

Konstantin8105 commented Feb 21, 2018

Copy link

This is a very good example of reflection. Thank you

Copy link

aorjoa commented Feb 28, 2020


Copy link

It is what exactly I wanted. :) It helps to save my time a lot. Thanks.

Copy link

nice example!!!

Copy link

Thank you! It's helpful for me!

Copy link

Thank You :)

Copy link

Great, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment