原文

This page describes exactly Go code the protocol buffer compiler generates for any given protocol definition. Any differences between proto2 and proto3 generated code are highlighted - note that these differences are in the generated code as described in this document, not the base API, which are the same in both versions. You should read the proto2 language guide and/or the proto3 language guide before reading this document.
这个文档准确描述了 protocol buffer 编译器如何根据给定的协议定义来生成 Go 代码。proto2 和 proto3 生成代码的差异会突出显示——请注意这些差异主要在本文档中描述的生成代码中,而不是两个版本中相同的基础 API。在阅读本文档前,您应该阅读 proto2 语言指南或 proto3 语言指南。

Compiler Invocation(编译器调用)

The protocol buffer compiler requires a plugin to generate Go code. Install it using Go 1.16 or higher by running:
protocol buffer 编译器需要一个插件来生成 Go 代码。 通过运行以下命令使用 Go 1.16 或更高版本安装它:

  1. go install google.golang.org/protobuf/cmd/protoc-gen-go@latest

This will install a protoc-gen-go binary in $GOBIN. Set the $GOBIN environment variable to change the installation location. It must be in your $PATH for the protocol buffer compiler to find it.
这将在 $GOBIN 中安装 protoc-gen-go 二进制文件。 设置 $GOBIN 环境变量以更改安装位置。 它必须在您的 $PATH 中,protocol buffer 编译器才能找到它。
The protocol buffer compiler produces Go output when invoked with the go_out flag. The argument to the go_out flag is the directory where you want the compiler to write your Go output. The compiler creates a single source file for each .proto file input. The name of the output file is created by replacing the .proto extension with .pb.go.
当使用 go_out 标志调用时,protocol buffer 编译器会生成 Go 输出。go_out 标志的参数是您希望编译器写入 Go 输出的目录。编译器为每个 .proto 文件输入创建一个源文件。输出文件的名称是通过将 .proto 扩展名替换为 .pb.go 来创建的。
Where in the output directory the generated .pb.go file is placed depends on the compiler flags. There are several output modes:
生成的 .pb.go 文件在输出目录中的位置取决于编译器标志。 有几种输出模式:

  • If the paths=import flag is specified, the output file is placed in a directory named after the Go package’s import path. For example, an input file protos/buzz.proto with a Go import path of example.com/project/protos/fizz results in an output file at example.com/project/protos/fizz/buzz.pb.go. This is the default output mode if a paths flag is not specified.
  • 如果指定了 paths=import 标志,则输出文件将放置在以 Go 包的导入路径命名的目录中。 例如,带有 example.com/project/protos/fizz 的 Go 导入路径的输入文件 protos/buzz.proto 会生成位于 example.com/project/protos/fizz/buzz.pb.go 的输出文件。 如果未指定路径标志,则这是默认输出模式。