How do I construct nested traits?

I have 2 traits Provider and Worker and provider gets a dynamic type of Worker

#[async_trait]
pub trait Provider<T:Worker> {
    async fn get(&self)->Option<T>;
}
pub trait Worker {}

When I try to use this type in a struct I get unused type Worker error

pub struct Foo<WP, W> // parameter `W` is never used
where
    WP: Provider<W>,
    W: Worker, {
        provider:WP
    }

I dont understand the problem since type W is clearly used in type WP

What if MyWP implements both Provider<P1> and Provider<P2>? Then W is not uniquely determined.

1 Like

There's a few ways to fix this:

  • Using an associated type:
#[async_trait]
pub trait Provider<T> {
    type W: Worker;
    async fn get(&self)->Option<Self::W>;
}
pub trait Worker {}

pub struct Foo<WP>
where
    WP: Provider<W>
{
    provider: WP
}
  • Using PhantomData:
#[async_trait]
pub trait Provider<T:Worker> {
    async fn get(&self)->Option<T>;
}
pub trait Worker {}

pub struct Foo<WP, W> // parameter `W` is never used
where
    WP: Provider<W>,
    W: Worker,
{
    provider: WP,
    phantom: std::marker::PhantomData<W>
}

associated type seems to be fixing my issue thanks

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.