I have a struct Foo
which a field of some type implementing a generic trait G, but I can't refer to this trait unless I also bind a type T, but then this leads to a compiler error:
type parameter
T
is never used. consider removingT
, referring to it in a field, or using a marker such asstd::marker::PhantomData
trait Trait {}
trait GenericTrait<T: Trait> {}
struct Foo<T, G>
where
T: Trait,
G: GenericTrait<T>,
{
t: G,
}
This can be solved by adding a PhantomData for T:
trait Trait {}
trait GenericTrait<T: Trait> {}
struct Foo<T, G>
where
T: Trait,
G: GenericTrait<T>,
{
t: G,
phantom: PhantomData<T>,
}
But this feels like tricking the compiler, and I'm wondering if there isn't a simpler solution that I'm missing here.
I've also considered to remove the bounds from the struct, but then I run into an error when trying to write an impl
block:
trait Trait {}
trait GenericTrait<T: Trait> {}
struct Foo<G> {
t: G,
}
impl<T: Trait, G: GenericTrait<T>> Foo<G> {}
This doesn't compile because the parameter T
is not used in the declaration.
Have you considered changing GenericTrait
to instead have an associated type instead of a type parameter, this would look like
trait GenericTrait {
type AssociatedType: Trait;
}
It would have the effect that now, for any implementing type T
, it can only implement GenericTrait
once, with one specific AssociatedType
, which may not be acceptable for your application, but if it is, then this would solve your issue because it's no longer necessary to provide the generic argument to GenericTrait
at all.