Protocol buffers 在Google protobuf中将默认枚举值设置为“未指定”的目的是什么?

Protocol buffers 在Google protobuf中将默认枚举值设置为“未指定”的目的是什么?,protocol-buffers,google-protocol-buffer,Protocol Buffers,Google Protocol Buffer,我可以看到,在Google Chrome Chrome sources中,第一个枚举值默认值被声明为未指定: // The type of a subresource filtering rule. enum RuleType { RULE_TYPE_UNSPECIFIED = 0; RULE_TYPE_COMMENT = 1; // Comment rule. RULE_TYPE_URL = 2; // Network level filtering rule bas

我可以看到,在Google Chrome Chrome sources中,第一个枚举值默认值被声明为未指定:

// The type of a subresource filtering rule.
enum RuleType {
  RULE_TYPE_UNSPECIFIED = 0;

  RULE_TYPE_COMMENT = 1;  // Comment rule.
  RULE_TYPE_URL = 2;      // Network level filtering rule based on URL pattern.
  RULE_TYPE_CSS = 3;      // Element hiding rule based on a CSS selector.
};

...

// Types of anchors that can be used to constrain where a URL pattern must
// begin/end in the URL in order to be considered a match.
enum AnchorType {
  ANCHOR_TYPE_UNSPECIFIED = 0;

  // Acts like a '*' wildcard at the respective end of a pattern.
  ANCHOR_TYPE_NONE = 1;
  // The pattern must match from the start/until the end of the URL.
  ANCHOR_TYPE_BOUNDARY = 2;
  // The pattern must match starting with the TLD+n of the URL's domain, but the
  // scheme and subdomains (if any) can be arbitrary.
  ANCHOR_TYPE_SUBDOMAIN = 3;
};
...
这样做的目的是什么

考虑到这一点,只需将字段设置为可选,就可以将字段标记为可选、必需和未指定的枚举值

比如说: :

但字段是可选的::


为什么不传递它而不是传递未指定的值呢?

也许最重要的原因是,如果您将来想要移动到proto3,那么提供一个干净的路径,因为这是唯一可以直接兼容的选项


然而,它也简化了许多平台上的使用,因为不同语言之间的枚举差异很大。这也使得默认值非常明显,因为可能是错误的-再次说明:默认新实例的初始化方式在不同平台/语言之间可能存在很大差异,而且您希望的控制级别在某些平台上可能不可用。

也许最重要的原因是,如果您将来想要移动到proto3,那么提供一条干净的路径,因为这是唯一可以直接兼容的选项


然而,它也简化了许多平台上的使用,因为不同语言之间的枚举差异很大。这也使得默认值非常明显,因为可能是错误的-再次说明:默认新实例的初始化方式在不同平台/语言之间可能存在很大差异,您希望的控制级别在某些平台上可能不可用。

我倾向于同意2017年使用protobuf 2迁移到protobuf 3的相关内容,当时protobuf 3已经存在,这看起来非常奇怪。那么,用一种明确的方式让我知道值很可能是错误的,这会让我想起magic value anti pattern,而不是根本没有任何价值。@4ntoine,这很好,但至少在某些语言/平台/框架上没有价值是不可能的,这是不合理的。x-plat的全部要点是,它需要在大多数平台上都可用。顺便说一句,我已经给谷歌的开发者发了一封电子邮件,写了这段代码。也许他可以解释,我倾向于同意2017年使用protobuf 2迁移到protobuf 3的相关内容,因为protobuf 3已经存在,看起来很奇怪。那么,用一种明确的方式让我知道值很可能是错误的,这会让我想起magic value anti pattern,而不是根本没有任何价值。@4ntoine,这很好,但至少在某些语言/平台/框架上没有价值是不可能的,这是不合理的。x-plat的全部要点是,它需要在大多数平台上都可用。顺便说一句,我已经给谷歌的开发者发了一封电子邮件,写了这段代码。也许他能解释
// The format of a URL pattern.
enum UrlPatternType {
  URL_PATTERN_TYPE_UNSPECIFIED = 0;

  // A pattern without special characters, e.g. "example.com".
  URL_PATTERN_TYPE_SUBSTRING = 1;

  // The pattern contains one or more wildcards, namely '*' and/or '^'
  // characters. The '*' matches any sequence of characters, while the '^'
  // matches a separator, i.e. anything but a letter, a digit, or one of [-._%].
  URL_PATTERN_TYPE_WILDCARDED = 2;

  // The pattern is a regular expression.
  URL_PATTERN_TYPE_REGEXP = 3;
};
 optional UrlPatternType url_pattern_type = 6;