dongmu3187 2015-11-01 01:07 采纳率: 0%
浏览 29
已采纳

如何在结构字段上使用类型切换(当字段属于接口类型时)?

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
", vv, vv)
        case TT:
            fmt.Printf("TT: vv=%T,%v
", vv, vv)
        case II:
            fmt.Printf("II: vv=%T,%v
", vv, vv)
        }
    }
}
  • 写回答

1条回答 默认 最新

  • dongqu5650 2015-11-01 01:31
    关注

    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
    ", ft.Name())
            case ft.Implements(IIType):
                fmt.Printf("II: %s
    ", ft.Name())
            default:
                fmt.Printf("??: %s %s
    ", ft.Kind(), ft.Name())
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
  • ¥15 Windows 系统cmd后提示“加载用户设置时遇到错误”
  • ¥50 vue router 动态路由问题
  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义