pub trait Generic {
type Repr: Repr;
// Required methods
fn into_repr(self) -> Self::Repr;
fn from_repr(repr: Self::Repr) -> Self;
fn as_repr(&self) -> <Self::Repr as Repr>::Ref<'_>;
fn as_mut_repr(&mut self) -> <Self::Repr as Repr>::Mut<'_>;
}
Expand description
类型与其表示的互转
Generic::Repr
提供了类型的表示,即其数据的结构。
拥有某类型的数据,可以通过 Generic::into_repr
转换成其表示,
或通过 Generic::from_repr
转换回来。
若有数据的引用,可以通过 Generic::as_repr
转换成引用形式的表示;
Generic::as_mut_repr
也类似。注意,引用形式的表示无法转换回来。
可以使用 derive 宏,在 struct 或 enum 上自动实现之。
它无法实现于 &T
或 &mut T
,因为无法实现 from_repr
。
类型的表示,是其底层类型的积的和,呈现为类型层面的列表。 它只体现结构,不包含其他信息,例如字段或变体的名字、枚举的值之类。 表示的伪代码如下:
repr ::= sums
sums ::= Zero | Sum<products, sums>
products ::= One | Product<type, products>
type ::= 任何类型,如 i32、()、Vec<String>
§举例
#[derive(Generic, Debug, PartialEq)]
enum E {
A(i32),
B(bool),
C,
}
assert_eq!(None::<i32>.into_repr(), Sum::This(One));
assert_eq!(<[_; 2]>::from_repr(Sum::This(Product(true, Product(false, One)))), [true, false]);
assert_eq!(E::B(true).as_repr(), Sum::Next(Sum::This(Product(&true, One))));
assert_eq!((1, E::A(1)).as_mut_repr(), Sum::This(Product(&mut 1, Product(&mut E::A(1), One))));
Required Associated Types§
Required Methods§
Sourcefn as_mut_repr(&mut self) -> <Self::Repr as Repr>::Mut<'_>
fn as_mut_repr(&mut self) -> <Self::Repr as Repr>::Mut<'_>
获取数据的表示的可变引用形式
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.