Search code examples
genericsrustoption-typetraits

Is it possible to have an optional generic type for a trait?


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.


Solution

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