Created
May 25, 2017 18:55
-
-
Save drgarcia1986/3749e6beadfb7135ceb6c765977989bc to your computer and use it in GitHub Desktop.
Ultra simple Golang Reflection example
This file contains 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
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