小编dpz*_*ick的帖子

将通用函数作为参数传递

我希望能够将泛型函数传递给另一个函数(在本例中为闭包),而不会丢失传递函数的"泛型".由于这是一个非常复杂的陈述,这是一个例子:

use std::fmt::Debug;

fn test<F, I: Debug>(gen: F) where F: Fn(fn(I) -> I) -> I {
    fn input<I: Debug>(x: I) -> I {
        x
    }

    println!("{:?}", gen(input));
}

fn main() {
    test(|input| {
        input(10);
        input(10.0)
    });
}
Run Code Online (Sandbox Code Playgroud)

这将无法编译,因为值的input类型是推断的,不再是通用的.

完整错误:

<anon>:14:15: 14:19 error: mismatched types:
 expected `_`,
    found `_`
(expected integral variable,
    found floating-point variable) [E0308]
<anon>:14         input(10.0)
                        ^~~~
Run Code Online (Sandbox Code Playgroud)

生锈有可能吗?

编辑:

基于给出的解决方案,我使用以下方法来解决类似的问题:

#![feature(unboxed_closures)]
#![feature(fn_traits)]

use std::ops::Fn;
use std::ops::Add;
use std::ops::FnMut;

use std::fmt::Debug;

struct Builder;

impl Builder {
    pub fn …
Run Code Online (Sandbox Code Playgroud)

rust

8
推荐指数
2
解决办法
1694
查看次数

标签 统计

rust ×1