Skip to content

Instantly share code, notes, and snippets.

@drgarcia1986
Created May 25, 2017 18:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drgarcia1986/3749e6beadfb7135ceb6c765977989bc to your computer and use it in GitHub Desktop.
Save drgarcia1986/3749e6beadfb7135ceb6c765977989bc to your computer and use it in GitHub Desktop.
Ultra simple Golang Reflection example
package main
import (
"fmt"
"reflect"
)
type sA struct {
foo int
bar string
}
type sB struct {
foo int
bar string
}
func main() {
a := sA{1, "hello"}
b := sB{2, "world"}
fmt.Println(intValue(a, "foo"), intValue(b, "foo"))
fmt.Println(strValue(a, "bar"), strValue(b, "bar"))
}
func strValue(s interface{}, fieldName string) string {
r := reflect.ValueOf(s)
f := reflect.Indirect(r).FieldByName(fieldName)
return f.String()
}
func intValue(s interface{}, fieldName string) int64 {
r := reflect.ValueOf(s)
f := reflect.Indirect(r).FieldByName(fieldName)
return f.Int()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment