1
votes

I need an optional generic type for a trait and I'm trying to figure out how to implement it in a nice way. Here's an example where I need it for a state struct:

impl<T> MyTrait<T> for MyStruct {
    type Value = MyState<T>;

    fn some_function(&self, state: &Self::Value) {
        ...
    }
    ...
}

Here's another example where I do not need it at all:

impl MyTrait for MyStruct {
    type Value = MyState;

    fn some_function(&self, state: &Self::Value) {
        ...
    }

    ...
}

The generic type is only used to define a field type in the MyState struct. The MyState struct itself is always defined in a completely different way depending on the use case and does not need a generic type in all cases.

I know there exists PhantomData<T> for structs with optional generic types and I was wondering if there was something similar for traits. Unfortunately, I haven't found anything yet.

Could I maybe just add another type with PhantomData<T>? Like this:

impl<T> MyTrait<T> for MyStruct {
    type Value = MyState;
    type Phantom = PhantomData<T>;

    fn some_function(&self, state: &Self::Value) {
        ...
    }
    ...
}

Rust would probably complain about an unused type.

Lastly, I'm adding this to a huge code base where the Trait structure is already given and used in many places. I hope that I do not need to touch much of the code already existing.

1
How would T be used in this context?E_net4 takes it literally
The State struct contains a HashMap<Identifier, T>. The State is used in a Graph Analysis where each node has a State. T is used to store different kinds of information in the map. In some cases the State struct does not have this map since the Graph Analysis is completely different.Melvin
Might it be appropriate to add PhantomData<T> to all existing State implementations? This way T would not need to be optional. It seems to me like a dirty workaround.Melvin
Please incorporate that information into the question. If made into a proper minimal reproducible example, the better.E_net4 takes it literally
Do you need MyTrait implemented for every T when implementing it for MyStruct? If not, you could impl MyTrait<()> for MyStruct { ... }.user4815162342

1 Answers

1
votes

If you don't need MyTrait<T> implemented for every kind of T, you can choose a dummy type to parameterize it for MyStruct:

impl MyTrait<()> for MyStruct {
    // ...
}