Skip to content

Instantly share code, notes, and snippets.

@gosuri
Created March 13, 2015 23:19
Show Gist options
  • Save gosuri/011383e88ea1bce67bd8 to your computer and use it in GitHub Desktop.
Save gosuri/011383e88ea1bce67bd8 to your computer and use it in GitHub Desktop.
Testing different runtime reflections in golang
// Testing different runtime reflections in golang
// See "The Laws of Reflection" for an introduction
// to reflection in Go: http://golang.org/doc/articles/laws_of_reflection.html
package main
import (
"fmt"
"reflect"
)
type TypeA struct {
Id int
FieldA string `tag: "field_a"`
}
func main() {
fmt.Println("For a pointer..")
ptr := &TypeA{1, "someval"}
displayReflection(ptr)
fmt.Println("\nFor a non pointer..")
val := TypeA{1, "someval"}
displayReflection(val)
}
func displayReflection(s interface{}) {
// ValueOf returns the concrete value
// stored in the interface
value := reflect.ValueOf(s)
sType := reflect.TypeOf(s)
fmt.Println("Kind of s:", value.Kind())
fmt.Println("Type of s:", sType)
// Elem returns the value that the interface s
// contains or that the pointer s points to
if value.Kind() == reflect.Ptr {
value = value.Elem()
fmt.Println("Kind of s elements:", value.Kind())
}
fmt.Println("Iterating on fields..")
for i := 0; i < value.NumField(); i++ {
field := value.Field(i)
fmt.Println(" Field:", i)
fmt.Println(" Name:", value.Type().Field(i).Name)
fmt.Println(" Tags:", value.Type().Field(i).Tag)
fmt.Println(" Kind:", field.Kind())
fmt.Println(" Value:", field)
}
}
@gosuri
Copy link
Author

gosuri commented Mar 13, 2015

To run the above:

$ go run $(o=/tmp/rfl.go;curl -sLo $o https://gist.githubusercontent.com/gosuri/011383e88ea1bce67bd8/raw/17c4d4a080955c4fe5b05a8c206a279bffdb5d39/reflections.go; echo $o)

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