Search code examples
rustrust-cargo

How to create a vector of generic functions in Rust


fn render_task_enter_field<W>(stdout: &mut W)
where
    W: Write,
{
    ...
}

I need to add this function to vector. I will iterate it and call each function.

I have tried Vec<fn(&mut impl Write)>, but it does not work

How can I call my function? I want to pass the variable described below to this function.

let mut stdout = stdout()
        .into_raw_mode()
        .expect("Cannot run raw mode")
        .into_alternate_screen()
        .expect("Cannot run alternate screen");

I use termion crate


Solution

  • You want this:

    Vec<Box<dyn Fn(&mut dyn Write)>>
    

    A vector of boxes containing a dynamic type of function that takes a dynamic object that implement write.

    You can't add generic functions to an array since it's really just a whole bunch of separate function, but you can just make it take a trait object as an argument to get the same effect.

    Full example:

    use std::io::Write;
    
    fn render_task_enter_field(stdout: &mut dyn Write)
    {
    }
    
    
    fn main() {
        let mut k:Vec<Box<dyn Fn(&mut dyn Write)>> = vec![];
    
        k.push(Box::new(render_task_enter_field));
       
        for m in k {
            m(&mut std::io::stdout());
        }
    }