Pass Generic Function as argument

后端 未结 2 1401
無奈伤痛
無奈伤痛 2021-01-04 11:22

I would like to be able to pass a generic function to another function (in this case a closure), without losing the "genericness" of the passed function. Since tha

2条回答
  •  醉梦人生
    2021-01-04 12:08

    As has been mentioned, unfortunately the call is monomorphized at the call site, so you cannot pass a generic function, you can only pass a monomorphized version of the generic function.

    What you can pass, however, is a function builder:

    use std::fmt::Debug;
    
    struct Builder;
    
    impl Builder {
        fn build(&self) -> fn(I) -> I {
            fn input(x: I) -> I { x }
            input
        }
    }
    
    fn test(gen: F)
        where F: Fn(Builder) -> T
    {
        let builder = Builder;
        println!("{:?}", gen(builder));
    }
    
    fn main() {
        test(|builder| {
            builder.build()(10);
            builder.build()(10.0)
        });
    }
    

    The Builder is able to generate instances of input on demand.

提交回复
热议问题