Skip to content

Instantly share code, notes, and snippets.

@rgaquino
Forked from drewolson/reflection.go
Last active November 7, 2019 04:57
Show Gist options
  • Select an option

  • Save rgaquino/33f30d5c840caa0a01f076c61d61242c to your computer and use it in GitHub Desktop.

Select an option

Save rgaquino/33f30d5c840caa0a01f076c61d61242c to your computer and use it in GitHub Desktop.
Golang Reflection Example
package main
import (
"fmt"
"reflect"
)
type Bar struct {
Gender string `tag_name:"gender"`
}
type Foo struct {
FirstName string `tag_name:"tag 1"`
LastName string `tag_name:"tag 2"`
Age int `tag_name:"tag 3"`
Others *Bar `tag_name:"tag 4"`
}
func doReflection(f interface{}) {
val := reflect.ValueOf(f).Elem()
for i := 0; i < val.NumField(); i++ {
valueField := val.Field(i)
typeField := val.Type().Field(i)
tag := typeField.Tag
if valueField.Kind() == reflect.Ptr {
fmt.Println("Found a pointer!")
doReflection(valueField.Interface())
}
fmt.Printf("Field Name: %s,\t Field Type: %v,\t Field Value: %v,\t Tag Value: %s\n", typeField.Name, typeField.Type, valueField.Interface(), tag.Get("tag_name"))
}
}
func main() {
f := &Foo{
FirstName: "Drew",
LastName: "Olson",
Age: 30,
Others: &Bar{
Gender: "male",
},
}
doReflection(f)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment