Newtype enums
An enum is considered a newtype if all of its variants is in the form of Variant( Type )
, e.g.
enum Value {
Bin( Vec<u8> ),
Text( String ),
}
is a newtype enum.
Prototypes of newtype enums
By erasing the name and all its variants' names of an enum, we get its prototype. For instance, the prototype of Value
is
enum __2 {
_0( Vec<u8> ),
_1( String ),
}
The prototype trait
pub trait Proto {
type Type;
fn from_proto( src: Self::Type ) -> Self;
fn into_proto( self ) -> Self::Type;
}
Can rustc auto-implement this trait for any user-defined enum
type?
impl Proto for Value {
type Type = std::enum_proto::__2;
fn from_proto( src:: Self::Type ) -> Self {
match src {
std::enum_proto::__2::_0(v) => Value::Bin(v),
std::enum_proto::__2::_1(v) => Value::Text(v),
}
}
fn into_proto( self ) -> Self::Type {
match self {
Value::Bin(v) => std::enum_proto::__2::_0(v),
Value::Text(v) => std::enum_proto::__2::_1(v),
}
}
}
Purpose of enum prototype
It is helpful for simulating language features ad-hoc enums, anonymous enums, structural enums, ... you name it.