3

Is it possible to omit or pass some "any" type?

I want to be able to define a single "queue" which can be used by registering processors for the different jobs. Similar to how bull queue in Node works.

The queue shouldn't care about the <P, R> generics on the processors. Its only job would be to enqueue a job, get the processor for that job (associated with the "name" the processor is registered with) and forward the job to it.

However, the processors property on the Queue struct needs some generic type to be passed to it. I tried to get around this by using a trait, but I am kind of back where I started.

I think I am trying to mimic the TypeScript any type.

I have seen suggestions to use an enum which would specify the different job types; however, this would complicate the processor of creating a reusable queue imo.

If I were to do this, instead of letting the user just register different processors, they would have to register them as well as modifying the enum for the new job type. Additionally, since the jobs are matched based on the associated processor, there wouldn't be the benefit to pattern matching.

The dyn Trait seems to be what I am looking for. However, I don't see how it works when the trait has associated types.

#[derive(Debug)]
struct JobOptions {}

#[allow(unused)]
#[derive(Debug)]
struct Job<P, R> {
    processor: String,
    payload: Box<P>,
    response: Option<Box<R>>,
    options: Option<JobOptions>,
    status: JobStatus,
}

#[allow(unused)]
struct Processor<P, R> {
    name: String,
    queue: VecDeque<Rc<Cell<Job<P, R>>>>,
}

trait JobProcessor {
    type Payload;
    type Response;
}

impl<P, R> JobProcessor for Processor<P, R> {
    type Payload = P;
    type Response = R;
}

#[derive(Default)]
struct Queue {
    processors: HashMap<String, Rc<Cell<JobProcessor<?, ?>>>>,
}
kyle
  • 2,563
  • 6
  • 22
  • 37
  • 1
    I believe your question is answered by the answers of [How can I avoid a ripple effect from changing a concrete struct to generic?](https://stackoverflow.com/q/44912349/155423) or [How can I have a collection of objects that differ by their associated type?](https://stackoverflow.com/q/28932450/155423). If you disagree, please **[edit]** your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Mar 27 '19 at 18:36
  • 3
    The `dyn Trait` is very similar to what I am looking for but it doesn't seem to address when the Trait has associated types. The other question suggests to use an enum; however, that complicates the ability for registering new processors. – kyle Mar 27 '19 at 19:11
  • I believe this is relevant: https://stackoverflow.com/a/58681952/516188 seems this is not possible in rust. – Emmanuel Touzery Mar 11 '21 at 17:09

0 Answers0