The following example is the simplest I can come up with to try to illustrate what I’m struggling to achieve:
pub trait Recipient {
fn receive(number: i32);
}
pub trait RecipientCatalog<R: Recipient> {
fn lookup<'a>(recipient_index: usize) -> &'a R;
}
pub struct NumberDispatch<C>
where C: RecipientCatalog<R> {
catalog: C
}
impl<C> NumberDispatch<C>
where C: RecipientCatalog<R> {
pub fn dispatch(&self, number: i32) {
let recipient_index = 0; // Would be lookup logic
self.catalog.lookup(recipient_index).receive(number);
}
}
In the example, the NumberDispatch should be able to dispatch a given number to some resolved Recipient implementation (lookup logic is not important for the example). However, this code does not compile as it is as type “R” is not defined. But I can not figure out how to define what R is in the NumberDispatch struct.
The idea is that the API user will provide a RecipientCatalog of some type, that provides references to something that implement the Recipient trait. Then the NumberDispatch should be able to pass a number to some resolved Recipient, by looking it up in the provided RecipientCatalog implementation.
This implies that the NumberDispatch define a generic constrained to a RecipientCatalog implementation. But since the RecipientCatalog also define a generic type constrained to the Recipient trait, I can’t figure out a way to define this in the NumberDispatch struct.
Does anyone know if and how something like this could be done?