Reputation: 3275
In Rust's chrono library there is this code in src/format/mod.rs#L338-L345:
pub struct ParseError(ParseErrorKind);
enum ParseErrorKind {
OutOfRange,
...
}
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?struct
syntax? Why not use ParseErrorKind
as a type directly (instead of wrapping it into a struct)?Upvotes: 3
Views: 654
Reputation: 42746
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?
It is a tuple struct, which in this case wraps an inner error type.
The main difference from other structs is that fields are not named. Instead they are accessed like tuples (ex my_instace.0
, to refer to the inner data).
Refer to the docs for more info
What is the advantage of using this struct syntax? Why not use ParseErrorKind as a type directly (instead of wrapping it into a struct)?
In this case it abstract the enum constructors over a single type. My guess is that they decided that the error kind is an implementation detail and should not be exposed in the API. Notice that ParseErrorKind
is private while ParseError
is public (with private access to the single tuple inside).
Additionally, it is also a common pattern to wrap types in order to expand what those types can do if those types are not native to your own crate.
Upvotes: 4