简体   繁体   English

协议缓冲区文件中使用的 go_package 选项是什么?

[英]What is the go_package option used for in a protocol buffer file?

I did some research including looking at the official doc from google and I can't find a good explanation of what the go_package option is used for.我做了一些研究,包括查看谷歌的官方文档,但我找不到go_package选项的用途的一个很好的解释。 The official doc states the following:官方文档声明如下:

The .proto file should contain a go_package option specifying the full import path of the Go package that contains the generated code. .proto文件应包含一个 go_package 选项,该选项指定包含生成代码的 Go package 的完整导入路径。

I guess what i'm confused with is what they mean by import path.我想我对导入路径的含义感到困惑。 It sounds more like an export path as in where we want to place the generated code?这听起来更像是一个导出路径,就像我们想要放置生成的代码一样? But why would we need this if we can specify the out path during --go_out= ?但是,如果我们可以在--go_out=期间指定输出路径,我们为什么需要这个? So i'm having trouble grasping why you need to specify an export path in the proto file and at the same time specify an output path in option go_package ?所以我很难理解为什么需要在 proto 文件中指定导出路径,同时在option go_package中指定 output 路径?

Declaring the generated codes expected import path is important for other protobuf files to know how to refer to those types in the generated code.声明生成的代码预期的导入路径对于其他 protobuf 文件了解如何在生成的代码中引用这些类型很重要。

If all of your protobuf definitions are declared in a single .proto file, the import path means little because they are implicitly sharing the same go package.如果您的所有 protobuf 定义都在单个.proto文件中声明,则导入路径意义不大,因为它们隐式共享相同的 go package。 If you start storing/generating protobuf files in multiple packages, they need to know how to find each other.如果您开始在多个包中存储/生成 protobuf 文件,它们需要知道如何找到彼此。

Looking at the protobuf "Well Known" types is a good example of this:查看 protobuf“众所周知”类型就是一个很好的例子:

https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/timestamp.proto https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/timestamp.proto

The top of that file has the following package declaration:该文件的顶部有以下 package 声明:

option go_package = "google.golang.org/protobuf/types/known/timestamppb";

If I consume that message in another protobuf file using:如果我在另一个 protobuf 文件中使用该消息:

import "google/protobuf/timestamp.proto";

message MyModel {
   google.protobuf.Timestamp ts = 1;
}

My generated file for MyModel will contain an import statement at the top of the .pb.go file that looks like:我为MyModel生成的文件将在.pb.go文件的顶部包含一个导入语句,如下所示:

import timestamppb "google.golang.org/protobuf/types/known/timestamppb"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM