场景
proto 中有个项是 oneof,但是最新的 gRPC generator并没有将此字段的接口导出。
Proto:
message Setting {
string item_id = 1; // 设置项的内部唯一id
string item_label = 2; // 设置项的名称
SettingItemType item_type = 3; // 设置项的类型
oneof attr {
SettingItemInputAttr input = 10;
SettingItemSelectAttr single_select = 11;
}
}
生成结果:
type isSetting_Attr interface {
isSetting_Attr()
}
type Setting_Input struct {
Input *SettingItemInputAttr `protobuf:"bytes,10,opt,name=input,proto3,oneof"`
}
type Setting_SingleSelect struct {
SingleSelect *SettingItemSelectAttr `protobuf:"bytes,11,opt,name=single_select,json=singleSelect,proto3,oneof"`
}
func (*Setting_Input) isSetting_Attr() {}
func (*Setting_SingleSelect) isSetting_Attr() {}
导致不便使用isSetting_Attr来限定指定字段的类型。
解决方案
解决方案为创建类型别名。在此案例中,通过在pb的同级目录(同一包内)为isSetting_Attr增加类型别名SettingAttr将其导出。
// SettingAttr
// https://github.com/golang/protobuf/issues/261#issuecomment-430496210
type SettingAttr = isSetting_Attr

使用案例(line:12)
