如何解决错误 "the precise format of `Fn`-family traits' type parameters is subject to change"?

How do I solve the error "the precise format of `Fn`-family traits' type parameters is subject to change"?

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

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

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

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

struct Test;
impl Fn<(f64,)> for Test {}

这会产生以下错误:

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)

我还想添加一个特征,其中包括 Fn 特征(不幸的是,我不知道如何定义)。这也可以吗?

编辑: 澄清一下:我已经用 C++ 开发了很长一段时间,C++ 解决方案是重载 operator()(args)。在那种情况下,我可以像函数一样使用 structclass。我希望能够

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

直接的答案就是完全按照错误信息所说的去做:

Use parenthetical notation instead

也就是说,使用 Fn(A, B)

而不是 Fn<(A, B)>

真正的问题是你

你问的真题更难确定,因为你没有提供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() {}