扩展Protobuf消息

use*_*793 11 inheritance serialization extends protocol-buffers

我有许多不同的模式,但是每个模式都包含一组字段.我想知道是否有办法让不同的模式扩展父模式并继承其字段.例如,这就是我想要的:

message Parent {
    required string common1 = 0;
    optional string common2 = 1;
}

message Child1 { // can we extend the Parent?
    // I want common1, common2 to be fields here
    required int c1 = 2;
    required string c2 = 3;
}

message Child2 { // can we extend Parent?
    // I want common1, common2 to be fields here
    repeated int c3 = 2;
    repeated string c4 = 3;
}
Run Code Online (Sandbox Code Playgroud)

这样Child1和Child2也包含来自Parent的字段common1和common2(可能更多).

这有可能吗?如果可以的话怎么样?

Rah*_*eel 8

这不是您问题的确切答案,但我们可以做类似的事情来共享通用参数。

message Child1 { 
    required int c1 = 2;
    required string c2 = 3;
}

message Child2 { 
    required int c1 = 2;
    required string c2 = 3;
}

message Request {
    required string common1 = 0;
    optional string common2 = 1;
    oneof msg { Child1 c1 = 2; Child2 c2 = 3; }

}
Run Code Online (Sandbox Code Playgroud)

其他选项是使用扩展关键字

message Parent {
    required string common1 = 0;
    optional string common2 = 1;
}

message Child1 { 
    extend Parent
    {       
        optional Child1 c1 = 100;
    }

    required int c1 = 2;
    required string c2 = 3;
}
Run Code Online (Sandbox Code Playgroud)

  • 原型缓冲区 3 中不支持扩展 (40认同)
  • 所以父母必须知道所有可能的孩子,它们可以在不同的文件中......丑陋 (2认同)