简体   繁体   中英

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. 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.

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= ? 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 ?

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.

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. If you start storing/generating protobuf files in multiple packages, they need to know how to find each other.

Looking at the protobuf "Well Known" types is a good example of this:

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

The top of that file has the following package declaration:

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

If I consume that message in another protobuf file using:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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