Is there any way to push or insert function to Vec or HashMap or HashSet?

Push a function to Vec:


fn one() -> (){
    println!("one");
    ()
}


fn main() {
    let mut fns:Vec<dyn Fn<()>> = Vec::new();
    fns.push(one);

    println!("{}", task());
    let _ = fns.iter().map(|f|f()).collect();
}

How to implement it?

something like this???

fn one() {
    println!("one")
}

fn two() {
    print!("two")
}

fn main() {
    let mut v: Vec<fn()> = Vec::new();
    v.push(one);
    v.push(two);
    for f in v {
        f()
    }
}

2 Likes

:+1: :+1:

If you want to also support closures, you can write it like this:


fn main() {
    let mut fns:Vec<Box<dyn Fn()>> = Vec::new();
    fns.push(Box::new(one));

    fns.iter().for_each(|f| f());
}

Note that this will be a little less performant than @elsuizo's solution, due to the boxing.

3 Likes

Thank you!

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.