如何解决错误"Fn`-族特征'类型参数的精确格式可能会发生变化"?

hfh*_*hc2 4 traits rust

我在Rust中编写了一个问题解决器,作为子程序需要调用一个以黑盒子形式给出的函数(基本上我想给出一个类型的参数Fn(f64) -> f64).

基本上我有一个定义的函数,fn solve<F>(f: F) where F : Fn(f64) -> f64 { ... }这意味着我可以solve像这样调用: solve(|x| x);

我想要做的是将更复杂的函数传递给求解器,即依赖于多个参数等的函数.

我希望能够将具有合适特征实现的结构传递给求解器.我尝试了以下方法:

struct Test;
impl Fn<(f64,)> for Test {}
Run Code Online (Sandbox Code Playgroud)

这会产生以下错误:

error: the precise format of `Fn`-family traits' type parameters is subject to change. Use parenthetical notation (Fn(Foo, Bar) -> Baz) instead (see issue #29625)
Run Code Online (Sandbox Code Playgroud)

我还想添加一个包含Fn特征的特征(不幸的是我不知道如何定义).那可能吗?

编辑:只是为了澄清:我已经用C++开发了很长一段时间,C++解决方案将重载operator()(args).在那种情况下,我可以使用structclass类似的功能.我希望能够

  1. 将两个函数和结构作为参数传递给求解器.
  2. 有一个简单的方法来调用函数.调用obj.method(args)obj(args)(在C++中)更复杂.但似乎这种行为目前无法实现.

She*_*ter 6

直接的答案是完全按照错误消息说的那样做:

请改用括号表示法

也就是说,而不是Fn<(A, B)>使用Fn(A, B)

真正的问题是,你不能落实Fn*性状自己稳定的锈的家庭.

你要问的真正问题是难以确定的,因为你没有提供MCVE,所以我们沦为猜测.我会说你应该把它翻过来; 创建一个新的特征,为闭包和你的类型实现它:

trait Solve {
    type Output;
    fn solve(&mut self) -> Self::Output;
}

impl<F, T> Solve for F
where
    F: FnMut() -> T,
{
    type Output = T;

    fn solve(&mut self) -> Self::Output {
        (self)()
    }
}

struct Test;
impl Solve for Test {
    // interesting things
}

fn main() {}
Run Code Online (Sandbox Code Playgroud)