Created
March 13, 2015 23:19
-
-
Save gosuri/011383e88ea1bce67bd8 to your computer and use it in GitHub Desktop.
Testing different runtime reflections in golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To run the above: