Protobuf3 使用其他消息類型
您可以使用其他消息類型作為字段類型。例如,假設您希望在每個SearchResponse消息中包含Result消息,為此,您可以在.proto中定義結果消息類型,然后在SearchResponse中指定Result類型字段:
message SearchResponse { repeated Result results = 1; } message Result { string url = 1; string title = 2; repeated string snippets = 3; }
導入定義
在上面的例子中,Result 消息類型和SearchResponse定義在同一個文件中——如果你想用作字段類型的消息類型已經在另一個.proto 文件中定義了呢?
您可以通過導入其他.proto文件來使用文件中的定義的類型。 您可以在文件的頂部添加一條import語句:
import "myproject/other_protos.proto";
默認情況下,您只能使用直接導入的 .proto文件定義。然而,有時你可能需要移動一個 .proto文件到一個新的位置,但不想為此更新了所有調用它的.proto文件,現在你可以在文件原始位置放置一個仿造的 .proto文件,使用import public將所有導入轉發到新位置。任何包含import public語句的proto的人都可以臨時依賴import public依賴。例如:
// new.proto // All definitions are moved here // old.proto // This is the proto that all clients are importing. import public "new.proto"; import "other.proto"; // client.proto import "old.proto"; // You use definitions from old.proto and new.proto, but not other.proto
協議編譯器使用-I/--proto_path標志在協議編譯器命令行指定的一組目錄中搜索導入的文件。如果沒有給出標志,它會在調用編譯器的目錄中查找。通常,您應該將--proto_path標志設置為項目的根目錄,並對所有導入使用完全限定的名稱。
使用proto2消息類型
可以導入proto2消息類型並在proto3消息中使用它們,反之亦然。但是,proto2枚舉不能直接在proto3語法中使用(如果導入的proto 2消息使用它們也沒關系)。