Skip to content

Instantly share code, notes, and snippets.

@drewolson
Last active November 21, 2024 15:11
Show Gist options
  • Save drewolson/4771479 to your computer and use it in GitHub Desktop.
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()
}
@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