dourao1896 2019-09-11 09:15
浏览 690
已采纳

如何在golang proto中获取所有字段名称生成复杂的结构

I am trying to get all the fields names in the go file generated from proto. Below is the generated struct.

type Action struct {
    Name             string            `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
    // Types that are valid to be assigned to ActionType:
    //  *Action_TaskAction
    ActionType           isAction_ActionType `protobuf_oneof:"action_type"`
}

As it is seen that ActionType is oneof Field in proto which is implemented as below.

type isAction_ActionType interface {
    isAction_ActionType()
}

type Action_TaskAction struct {
    TaskAction *TaskAction `protobuf:"bytes,16,opt,name=task_action,json=taskAction,proto3,oneof"`
}

type TaskAction struct {
    Progress             float32  `protobuf:"fixed32,1,opt,name=progress,proto3" json:"progress,omitempty"`
}

As I want to get the field name in TaskAction struct which is Progress.

I am using below code to get the field names but facing issue if the field type is interface(for oneof field)

func printFieldNames(t reflect.Type) error {
    for i := 0; i < t.NumField(); i++ {
        field := t.Field(i)
        if field.Type.Kind() == reflect.Struct {
            printFieldNames(field.Type)
            continue
        }
        if field.Type.Kind() == reflect.Interface {
            // what to do here.
        }
        column := field.Tag.Get("json")
        fmt.Println("column: ", column)
    }
    return nil
}
  • 写回答

1条回答 默认 最新

  • duanli3277 2019-09-11 09:42
    关注

    If the type is interface, you can't do much about that. In an actual value it may be a struct or any other type that implements that interface, but the interface type itself cannot tell you this, it does not restrict the concrete type.

    You may do what you want if you start with reflect.Value instead of reflect.Type, because if you have a value, you can examine the value (or its type) that is stored in the interface. To get the reflect.Value descriptor wrapped in an interface value, you may use reflect.Elem().

    Also, to handle pointer to structs, you again may use reflect.Elem() to get the pointed value. You may check if a value is a pointer by comparing its kind to reflect.Ptr.

    Here's an example of your printFieldNames(), rewritten to work with reflect.Value, and it recurses into structs stored in interface values. This is not a solution that handles all cases, but demonstrates how to do it:

    func printFieldNames(v reflect.Value) {
        for i := 0; i < v.NumField(); i++ {
            field := v.Field(i)
            if field.Kind() == reflect.Ptr {
                field = field.Elem()
            }
            if field.Kind() == reflect.Struct {
                printFieldNames(field)
                continue
            }
            if field.Kind() == reflect.Interface {
                wrapped := field.Elem()
                if wrapped.Kind() == reflect.Ptr {
                    wrapped = wrapped.Elem()
                }
                printFieldNames(wrapped)
            }
            structfield := v.Type().Field(i)
            column := structfield.Tag.Get("json")
            fmt.Printf("column: %s, json tag: %s
    ", structfield.Name, column)
        }
    }
    

    Testing it:

    a := Action{
        ActionType: Action_TaskAction{
            TaskAction: &TaskAction{},
        },
    }
    printFieldNames(reflect.ValueOf(a))
    

    Output will be (try it on the Go Playground):

    column: Name, json tag: name,omitempty
    column: Progress, json tag: progress,omitempty
    column: ActionType, json tag: 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)