我可以看到,在 Google Chrome (Chromium) 源中,第一个枚举值(默认)被声明为“未指定”:
// 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;
};
...
Run Code Online (Sandbox Code Playgroud)
https://cs.chromium.org/chromium/src/components/url_pattern_index/proto/rules.proto
这样做的目的是什么?
考虑到它是protobuf2,因此字段可以用optionaland标记,required并且unspecified只需将字段设置为可选即可删除枚举值。
比方说: https: //cs.chromium.org/chromium/src/components/url_pattern_index/proto/rules.proto ?l=22 :
// 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;
};
Run Code Online (Sandbox Code Playgroud)
但该字段是optional: https: //cs.chromium.org/chromium/src/components/url_pattern_index/proto/rules.proto ?l=150 :
optional UrlPatternType url_pattern_type = 6;
Run Code Online (Sandbox Code Playgroud)
为什么不传递它而不是传递unspecified值?
也许最重要的原因是如果您将来想迁移到 proto3,请提供一条干净的路径,因为这是唯一直接兼容的选项。
然而,它也简化了在许多平台上的使用,因为不同语言之间的枚举差异很大。它还使默认值非常明显地被认为“可能是错误的”——同样:默认的新实例的初始化方式在平台/语言之间可能会有很大差异,并且您希望的控制级别可能在某些平台上不可用。