dongxi7609 2017-01-17 10:27 采纳率: 0%
浏览 82
已采纳

如何使用反射来检查结构字段的类型是否为interface {}?

I am using the reflect package to determine the type of a struct field is interface{}

I want to do the comparison like so (where t is a reflect.Type):

if  t == reflect.TypeOf(interface{}) {

}

The problem is that the compiler complains: type interface {} is not an expression.

Is there anyway to check if the type of a struct field is an interface{}?

  • 写回答

2条回答 默认 最新

  • doucang2831 2017-01-17 12:30
    关注

    interface{} is a type, and reflect.TypeOf() expects a value. So you can't pass the literal interface{} to it. You can only pass a value.

    Back to the original question. Let's see a struct example:

    type My struct {
        A int
        B interface{}
        C io.Reader
    }
    

    You want to tell if the type of a field is interface{}. Acquire the reflect.Type of the struct type, then you can access the fields using Type.Field() or Type.FieldByName().

    This gives you a value of type reflect.StructField which stores the type of the field.

    So far so good. But what should we compare it to? interface{} is an interface type with 0 methods. You can't have (instantiate) a value of that type. You can only have values of concrete types, but yes, they may be wrapped in an interface type.

    You could use Type.Kind, and compare it to reflect.Interface, which tells you if it's an interface, but this is true for all interface types. You could also check if it has 0 methods with Type.NumMethod(), which must be 0 for interface{}, but other interfaces could also have 0 methods...

    You may use Type.Name, but since interface{} is a unnamed type, its name is the empty string "" (and there are other unnamed types). You may use Type.String() which returns "interface {}" for the empty interface:

    t := reflect.TypeOf(My{})
    
    for i := 0; i < t.NumField(); i++ {
        f := t.Field(i)
        fmt.Printf("Field %q, type: %-12v, type name: %-8q, is interface{}: %v
    ",
            f.Name, f.Type,
            f.Type.Name(),
            f.Type.String() == "interface {}",
        )
    }
    

    Output (try it on the Go Playground):

    Field "A", type: int         , type name: "int"   , is interface{}: false
    Field "B", type: interface {}, type name: ""      , is interface{}: true
    Field "C", type: io.Reader   , type name: "Reader", is interface{}: false
    

    You might find this related question interesting / useful: Identify non builtin-types using reflect

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记