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

如何在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条回答

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 opencv c++虚拟画家
      • ¥20 python 生成exe报错问题
      • ¥15 基于香农-费诺-埃利斯编码实现对英文文本的压缩和解压缩
      • ¥15 react native ios端amap问题
      • ¥15 fortran95中5个学生分不同学号求数学语文英语计算机四门课程的每名学生的平均分以及名次以及单科成绩的平均分
      • ¥30 excel vba 执行从 1 到 100 的乘法。执行结果保存成二维数组
      • ¥15 数字电子技术基础设计实验
      • ¥15 ue5运行非常卡顿,是电脑配置原因吗
      • ¥50 有没有大佬看一下关于思科的这道题怎么做
      • ¥30 求十字路口交通灯S7-200plc,今天早上八点前。