你必须依靠构图:
pub struct TypeDataInner {
pub a_symbol: &'static str,
pub b_symbol: &'static str,
pub c_symbol: &'static str,
}
pub enum TypeData {
Type1(TypeDataInner),
Type2(TypeDataInner),
}
impl TypeData {
pub fn type1() -> TypeData {
TypeData::Type1(TypeDataInner {
// ...
}
}
pub fn type2() -> TypeData {
TypeData::Type2(TypeDataInner {
// ...
}
}
}
另一个选择是使用
PhantomData
哪一个
will encode type information that gets erased after compilation
:
pub struct TypeData<Type> {
pub a_symbol: &'static str,
pub b_symbol: &'static str,
pub c_symbol: &'static str,
_type: core::marker::PhantomData<Type>,
}
impl<T> TypeData<T> {
pub fn type_t() -> TypeData<T> {
TypeData {
a_symbol: "",
b_symbol: "",
c_symbol: "",
_type: core::marker::PhantomData,
}
}
}
struct Tr;
fn main() {
TypeData::<Tr>::type_t();
}