Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 770
Melvin Avatar asked Oct 17 '25 21:10

Melvin


1 Answers

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 {
    // ...
}
like image 71
user4815162342 Avatar answered Oct 19 '25 18:10

user4815162342



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!