#Vector of mixed closures types

5 messages · Page 1 of 1 (latest)

autumn crypt
#

Hi folks !

I have a problem / question with generics. I don't even know if what i'm trying to do is doable....

I have a vector of structs that contain a closure :

pub struct Handling<'a, E>{
    pub handler: Box<dyn FnMut(&mut Arg) -> Result<(), E> + 'a>,
}

pub type Handlers<'a, E> = Vec<Handling<'a,E>>;

The thing is, in my code, I do this :

let handlers : Handlers = vec![
  Handling {
  handler : Box::from(|my_arg| { cast_function::<TypeA>(my_arg); ...}
},
  Handling {
  handler : Box::from(|my_arg| { cast_function::<TypeB>(my_arg); ...}
},
  Handling {
  handler : Box::from(|my_arg| { cast_function::<TypeC>(my_arg); ...}
},
]

I would LOVE to refactor this, in order to inject TypeA / TypeB / TypeC instead of my_arg into my closure parameter !

But is it possible ??? It would require to mix different generics in the same Vector, and I really don't know how to tackle the problem.

Note: I oversimplified the code in order to showcase my problem, I know my example doesn't compile, but my code do !

tender dome
#

you mean, you want each function to take TypeA (etc.) instead of the single type Arg?

#

you can do this, but what you have to do is wrap the function in a struct, make that struct implement a trait, and make a Vec<Box<dyn ThatTrait>>

#

and the implementation has to deal with however you get a TypeA to call the function, of course

#

the key is that all of the parts of the code that contain a specific type must be inside, not outside of the trait