我可以更改原型文件中的编号标签吗?

Can I change the numbered tags in a proto file?

This post 描述了 proto 文件中编号标签的用途,本质上是在序列化和反序列化数据时匹配字段。我的问题是:如果我更改现有字段的编号会怎样?

同样的例子,假设这是原始数据

message SearchRequest {
  required string query = 1;
  // Pagination fields
  optional int32 page_number = 2;
  optional int32 result_per_page = 3;
}

我想添加一个新字段,将其放在分页字段之前在逻辑上是有意义的 - 如果我不使用 page_number 和 [=,我可以重新枚举如下字段吗13=] 个字段(尽管消息类型 SearchRequest 正在使用中)?

message SearchRequest {
  required string query = 1;
  optional int32 new_data = 2;
  // Pagination fields
  optional int32 page_number = 3;
  optional int32 result_per_page = 4;
}

我是否应该从一开始就给分页字段更高的数字以允许新字段?

documentation

These field numbers are used to identify your fields in the message binary format, and should not be changed once your message type is in use.

更改字段编号几乎总是一个坏主意 - 你会得到非常奇怪的行为,除非所有客户端和服务器 are.deployed 在完全相同的时间并且任何地方都没有持久有效负载数据(在文件,数据库中, ETC)。特别是,序列化器会尝试将数据解释为不同的东西:在某些情况下,这会导致序列化失败,而在其他情况下,它会默默地愉快地反序列化数据 具有垃圾意义,造成混乱。

没有理由不简单地使用字段 5。