doushan2311 2016-10-05 06:05
浏览 33
已采纳

从界面获取所有字段

How do I know the fields I can access from the reply object/interface? I tried reflection but it seems you have to know the field name first. What if I need to know all the fields available to me?

// Do sends a command to the server and returns the received reply.
Do(commandName string, args ...interface{}) (reply interface{}, err error)
  • 写回答

1条回答 默认 最新

  • douhuang2282 2016-10-05 06:17
    关注

    You can use the reflect.TypeOf() function to obtain a reflect.Type type descriptor. From there, you can list fields of the dynamic value stored in the interface.

    Example:

    type Point struct {
        X int
        Y int
    }
    
    var reply interface{} = Point{1, 2}
    t := reflect.TypeOf(reply)
    for i := 0; i < t.NumField(); i++ {
        fmt.Printf("%+v
    ", t.Field(i))
    }
    

    Output:

    {Name:X PkgPath: Type:int Tag: Offset:0 Index:[0] Anonymous:false}
    {Name:Y PkgPath: Type:int Tag: Offset:4 Index:[1] Anonymous:false}
    

    The result of a Type.Field() call is a reflect.StructField value which is a struct, containing the name of the field among other things:

    type StructField struct {
        // Name is the field name.
        Name string
        // ...
    }
    

    If you also want the values of the fields, you may use reflect.ValueOf() to obtain a reflect.Value(), and then you may use Value.Field() or Value.FieldByName():

    v := reflect.ValueOf(reply)
    for i := 0; i < v.NumField(); i++ {
        fmt.Println(v.Field(i))
    }
    

    Output:

    1
    2
    

    Try it on the Go Playground.

    Note: often a pointer to struct is wrapped in an interface. In such cases you may use Type.Elem() and Value.Elem() to "navigate" to the pointed type or value:

    t := reflect.TypeOf(reply).Elem()
    
    v := reflect.ValueOf(reply).Elem()
    

    If you don't know whether it's a pointer or not, you can check it with Type.Kind() and Value.Kind(), comparing the result with reflect.Ptr:

    t := reflect.TypeOf(reply)
    if t.Kind() == reflect.Ptr {
        t = t.Elem()
    }
    
    // ...
    
    v := reflect.ValueOf(reply)
    if v.Kind() == reflect.Ptr {
        v = v.Elem()
    }
    

    Try this variant on the Go Playground.

    For a detailed introduction to Go's reflection, read the blog post: The Laws of Reflection.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码