代码之家  ›  专栏  ›  技术社区  ›  stacksonstacks

是否缺少一些心理模型或模式i_m来适应需要更复杂字段的各种不可变形式的类型?[关闭]

  •  0
  • stacksonstacks  · 技术社区  · 6 年前

    i_m尝试表示一种类型,这种类型可以具有各种不可变形式(听起来像枚举),但需要更复杂的字段。

    每个变量将具有相同的字段,但将通过设置的值进行区分。

    当前实现使用不同的构造函数返回给定类型的实例,但是结构本身没有编码类型信息。

    我似乎发现自己又回到了 this RFC 有类似的问题。

    是否有一些心理模型或模式i_m缺失以适应生锈?

    pub struct TypeData {
        pub a_symbol: &'static str,
        pub b_symbol: &'static str,
        pub c_symbol: &'static str,
    }
    
    impl TypeData {
        pub fn type1() -> TypeData {
            TypeData  {
                // ...
            }
        }
    
        pub fn type2() -> TypeData {
            TypeData {
                // ...
            }
        }
    }
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Shepmaster Tim Diekmann    6 年前

    你必须依靠构图:

    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();
    }
    
    推荐文章