Encoding types with struct + enum combinations

#1

Hi All,

I’m trying to represent a type which can have various immutable forms (sounds like an enum) but needs more complex fields.
The current solution uses a different constructor to return an instance of a given type, however there’s no type information encoded in the struct itself.

I seem to find myself coming back to this RFC again and again with similar problems.

Is there some mental model or pattern I’m missing to adapt this in rust?

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 {
            // ...
        }
    }
}
0 Likes

#2

Can you elaborate what do you mean by complex fields and immutable forms?

Rust’s enums can have fields, and can contain structs if you need a different implementation for each.

Do you need something like associated constants for each variant?

0 Likes

#3

Hey,
Complex as in embedding a struct within the enum would be required

Immutable forms as in each variant could / should be though of as a constant and read-only

Yes that sounds like what I’m after

0 Likes

#4

How about normal constants?

pub const TYPE1: TypeData = TypeData {...};
pub const TYPE2: TypeData = ...;

Mentioning how you’re going to use this data will influence the suggestions.

0 Likes

#5

Thanks @vitalyd
I’d like to match against the resulting types.

I’ve decided to go with an embedded struct in the enum. However I don’t like the API as I have to match and “unwrap” the enum to expose the underlying struct fields

0 Likes