See: http://play.golang.org/p/GDCasRwYOp
I have a need to do things based on the type of the struct fields.
The following does not work when a field is of interface type.
I think I get why this is not working. But is there a way to do what I want to do?
package main
import (
"fmt"
"reflect"
)
type TT struct {
Foo int
}
type II interface {
Bar(int) (int, error)
}
type SS struct {
F1 TT
F2 II
}
func main() {
var rr SS
value := reflect.ValueOf(rr)
for ii := 0; ii < value.NumField(); ii++ {
fv := value.Field(ii)
xv := fv.Interface()
switch vv := xv.(type) {
default:
fmt.Printf("??: vv=%T,%v\n", vv, vv)
case TT:
fmt.Printf("TT: vv=%T,%v\n", vv, vv)
case II:
fmt.Printf("II: vv=%T,%v\n", vv, vv)
}
}
}
Maybe this gets you where you want to go?
func main() {
var rr SS
typ := reflect.TypeOf(rr)
TTType := reflect.TypeOf(TT{})
IIType := reflect.TypeOf((*II)(nil)).Elem() // Yes, this is ugly.
for ii := 0; ii < typ.NumField(); ii++ {
fv := typ.Field(ii)
ft := fv.Type
switch {
case ft == TTType:
fmt.Printf("TT: %s\n", ft.Name())
case ft.Implements(IIType):
fmt.Printf("II: %s\n", ft.Name())
default:
fmt.Printf("??: %s %s\n", ft.Kind(), ft.Name())
}
}
}