简体   繁体   中英

How do I use type switch on struct fields (when field is of interface type)?

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())
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM