将 Enum 定义为 Struct(为什么要使用这种语法)
Define Enum as a Struct (why use this syntax)
在 Rust 的 chrono library there is this code in src/format/mod.rs#L338-L345 中:
pub struct ParseError(ParseErrorKind);
enum ParseErrorKind {
OutOfRange,
...
}
- 第一行的语法
struct ParseError(ParseErrorKind)
是什么意思?枚举 ParseErrorKind
是否有点“别名”为名为 ParseError
的结构,或者 ParseError
是一个包含枚举类型 ParseErrorKind
的匿名字段的结构?如果是后者,将如何访问该字段?或者这是别的东西?
- 使用这种
struct
语法有什么好处?为什么不直接将 ParseErrorKind
用作类型(而不是将其包装到结构中)?
In the first line, what does the syntax struct ParseError(ParseErrorKind) mean? Is enum ParseErrorKind somewhat "aliased" as a struct called ParseError, or is ParseError a struct that contains an anonymous field of enum type ParseErrorKind? If the latter, how would one access the field? Or is this something else?
它是一个 tuple struct,在本例中它包装了一个内部错误类型。
与其他结构的主要区别是字段没有命名。相反,它们像元组一样访问(例如 my_instace.0
,以引用内部数据)。
请参阅 docs 了解更多信息
What is the advantage of using this struct syntax? Why not use ParseErrorKind as a type directly (instead of wrapping it into a struct)?
在这种情况下,它将枚举构造函数抽象为单一类型。我的猜测是他们认为错误 kind 是一个实现细节,不应在 API 中公开。请注意,ParseErrorKind
是私有的,而 ParseError
是 public(可以私有访问内部的单个元组)。
此外,包装类型也是一种常见的模式,以便在这些类型不是您自己的板条箱原生的情况下扩展这些类型的功能。
在 Rust 的 chrono library there is this code in src/format/mod.rs#L338-L345 中:
pub struct ParseError(ParseErrorKind);
enum ParseErrorKind {
OutOfRange,
...
}
- 第一行的语法
struct ParseError(ParseErrorKind)
是什么意思?枚举ParseErrorKind
是否有点“别名”为名为ParseError
的结构,或者ParseError
是一个包含枚举类型ParseErrorKind
的匿名字段的结构?如果是后者,将如何访问该字段?或者这是别的东西? - 使用这种
struct
语法有什么好处?为什么不直接将ParseErrorKind
用作类型(而不是将其包装到结构中)?
In the first line, what does the syntax struct ParseError(ParseErrorKind) mean? Is enum ParseErrorKind somewhat "aliased" as a struct called ParseError, or is ParseError a struct that contains an anonymous field of enum type ParseErrorKind? If the latter, how would one access the field? Or is this something else?
它是一个 tuple struct,在本例中它包装了一个内部错误类型。
与其他结构的主要区别是字段没有命名。相反,它们像元组一样访问(例如 my_instace.0
,以引用内部数据)。
请参阅 docs 了解更多信息
What is the advantage of using this struct syntax? Why not use ParseErrorKind as a type directly (instead of wrapping it into a struct)?
在这种情况下,它将枚举构造函数抽象为单一类型。我的猜测是他们认为错误 kind 是一个实现细节,不应在 API 中公开。请注意,ParseErrorKind
是私有的,而 ParseError
是 public(可以私有访问内部的单个元组)。
此外,包装类型也是一种常见的模式,以便在这些类型不是您自己的板条箱原生的情况下扩展这些类型的功能。