Skip to content

Instantly share code, notes, and snippets.

@drewolson
Last active November 20, 2023 09:39
Star You must be signed in to star a gist
Save drewolson/4771479 to your computer and use it in GitHub Desktop.
Golang Reflection Example
package main
import (
"fmt"
"reflect"
)
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,
}
f.reflect()
}
@rogierlommers
Copy link

Thanks!

@sofyan-ahmad
Copy link

Thank you! 👍

@johnstevin
Copy link

很好的例子,感谢作者!
thanks to the author,A good example!

@sdtsui
Copy link

sdtsui commented Sep 22, 2016

thanks @drewolson, and @lenw for posting the snippet

@rmasci
Copy link

rmasci commented Feb 14, 2017

yeah this helped me a lot!!

@maxymania
Copy link

This is a good example. Thanks.

@huzhengchuan
Copy link

good example. tks

@manigandand
Copy link

This is a good example. It helped me!

@oscarzhou
Copy link

So nice example. Hah, solve my problem perfectly

@Konstantin8105
Copy link

Konstantin8105 commented Feb 21, 2018

@babulal107
Copy link

This is a very good example of reflection. Thank you

@aorjoa
Copy link

aorjoa commented Feb 28, 2020

Thanks!!!

@TsuyoshiUshio
Copy link

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

@lemon-tree-sheng
Copy link

nice example!!!

@Lim79Plus
Copy link

Thank you! It's helpful for me!

@fishparmak
Copy link

Thank You :)

@maxim-ge
Copy link

Great, thanks!

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