生成GRPC Go代码时Protocol Buffers报错:Expected required/optional/repeated
Protocol Buffers生成GRPC代码报错解决方案
问题描述
生成GRPC代码时触发如下错误:
route_guide.proto:5:1: Expected "required", "optional", or "repeated".
使用的.proto文件内容如下:
message Point { int32 latitude = 1 ; int32 longitude = 2 ; } message Rectangle { Point lo = 1 ; Point hi = 2 ; } message Feature { string name = 1 ; Point location = 2 ; } message RouteNote { Point location = 1 ; string message = 2 ; } message RouteSummary { int32 point_count = 1 ; int32 feature_count = 2 ; int32 distance = 3 ; int32 elapsed_time = 4 ; } service RouteGuide{ rpc GetFeature(Point) returns (Feature) {} rpc ListFeatures(Rectangle) returns (stream Feature) {} rpc RecordRoute(stream Point) returns (RouteSummary) {} rpc RouteChat(stream RouteNote) returns (stream RouteNote) {} }
错误原因
你正在用**Protocol Buffers 2(PB2)的编译器编译遵循Protocol Buffers 3(PB3)**语法的文件。PB2要求所有字段必须显式声明required/optional/repeated修饰符,而PB3默认字段为optional(无需显式写出),官方Go GRPC教程使用的是PB3语法。
解决方案
方案1:添加PB3版本声明(推荐)
在.proto文件最顶部添加PB3语法声明,这是官方教程的标准写法,后续兼容性更好:
syntax = "proto3"; message Point { int32 latitude = 1 ; int32 longitude = 2 ; } // 其余内容保持不变
方案2:适配PB2语法(仅用于必须使用PB2的场景)
为每个字段添加optional修饰符,满足PB2的语法要求:
message Point { optional int32 latitude = 1 ; optional int32 longitude = 2 ; } message Rectangle { optional Point lo = 1 ; optional Point hi = 2 ; } // 其余所有字段同理添加optional修饰符
内容的提问来源于stack exchange,提问作者Tushar Gupta
相关产品推荐
相关产品推荐

