在protobuf中需要一个'oneof'?

2024-10-01 15:36:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我想制作一个protobufEvent消息,它可以包含几种不同的事件类型。下面是一个例子:

message Event {
    required int32 event_id = 1;

    oneof EventType {
        FooEvent foo_event = 2;
        BarEvent bar_event = 3;
        BazEvent baz_event = 4;
    }
}

这很好,但有一件事让我很恼火,那就是EventType是可选的:我只能用event_id来编码一个对象,protobuf不会抱怨。在

^{pr2}$

有什么方法可以要求设置EventType?我在用Python,如果这很重要的话。在


Tags: eventid消息类型messagefoorequired事件
1条回答
网友
1楼 · 发布于 2024-10-01 15:36:21

根据Protocol Buffers文档,不建议使用required字段规则,该规则已在proto3中删除。在

Required Is Forever You should be very careful about marking fields as required. If at some point you wish to stop writing or sending a required field, it will be problematic to change the field to an optional field – old readers will consider messages without this field to be incomplete and may reject or drop them unintentionally. You should consider writing application-specific custom validation routines for your buffers instead. Some engineers at Google have come to the conclusion that using required does more harm than good; they prefer to use only optional and repeated. However, this view is not universal.

正如上面的文档所说,您应该考虑使用特定于应用程序的验证,而不是将字段标记为required。在

没有办法将oneof标记为“required”(即使在proto2中也是如此),因为在引入oneof时,已经广泛接受字段可能永远不应该是“required”的,因此设计者不必费心实现一种使oneof成为必需的方法。在

相关问题 更多 >

    热门问题