如何在结构字段上使用类型开关(当字段为接口类型时)?

见:http : //play.golang.org/p/GDCasRwYOp


我需要根据结构字段的类型做一些事情。


当字段为接口类型时,以下内容不起作用。


我想我明白为什么这不起作用。但是有没有办法做我想做的事?


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)

        }

    }

}


慕森王
浏览 96回答 1
1回答

梦里花落0921

也许这会让你去你想去的地方?func main() {&nbsp; &nbsp; var rr SS&nbsp; &nbsp; typ := reflect.TypeOf(rr)&nbsp; &nbsp; TTType := reflect.TypeOf(TT{})&nbsp; &nbsp; IIType := reflect.TypeOf((*II)(nil)).Elem() // Yes, this is ugly.&nbsp; &nbsp; for ii := 0; ii < typ.NumField(); ii++ {&nbsp; &nbsp; &nbsp; &nbsp; fv := typ.Field(ii)&nbsp; &nbsp; &nbsp; &nbsp; ft := fv.Type&nbsp; &nbsp; &nbsp; &nbsp; switch {&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; case ft == TTType:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("TT: %s\n", ft.Name())&nbsp; &nbsp; &nbsp; &nbsp; case ft.Implements(IIType):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("II: %s\n", ft.Name())&nbsp; &nbsp; &nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("??: %s %s\n", ft.Kind(), ft.Name())&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go