我如何解决错误“'Fn'-family traits'类型参数的精确格式可能会发生变化"? [英] How do I solve the error "the precise format of `Fn`-family traits' type parameters is subject to change"?
问题描述
我用 Rust 编写了一个问题解决器,它作为子例程需要调用一个作为黑盒给出的函数(本质上我想给出一个 Fn(f64) -> 类型的参数;f64
).
I have written a problem solver in Rust which as a subroutine needs to make calls to a function which is given as a black box (essentially I would like to give an argument of type Fn(f64) -> f64
).
本质上我有一个函数定义为 fn solve
这意味着我可以像这样调用 solve
:solve(|x| x);
Essentially I have a function defined as fn solve<F>(f: F) where F : Fn(f64) -> f64 { ... }
which means that I can call solve
like this:
solve(|x| x);
我想做的是将一个更复杂的函数传递给求解器,即一个依赖于多个参数等的函数.
What I would like to do is to pass a more complex function to the solver, i.e. a function which depends on multiple parameters etc.
我希望能够将具有合适特征实现的结构传递给求解器.我尝试了以下方法:
I would like to be able to pass a struct with a suitable trait implementation to the solver. I tried the following:
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
特征(不幸的是,我不知道如何定义).这也可能吗?
I would also like to add a trait which includes the Fn
trait (which I don't know how to define, unfortunately). Is that possible as well?
澄清一下:我用 C++ 开发已经有一段时间了,C++ 的解决方案是重载 operator()(args)
.在那种情况下,我可以像函数一样使用 struct
或 class
.我希望能够
Just to clarify: I have been developing in C++ for quite a while, the C++ solution would be to overload the operator()(args)
. In that case I could use a struct
or class
like a function. I would like to be able to
- 将函数和结构体作为参数传递给求解器.
- 有一个简单的方法来调用函数.调用
obj.method(args)
比obj(args)
(在 C++ 中)更复杂.但目前似乎无法实现这种行为.
- Pass both functions and structs to the solver as arguments.
- Have an easy way to call the functions. Calling
obj.method(args)
is more complicated thanobj(args)
(in C++). But it seems that this behavior is not achievable currently.
推荐答案
直接的答案是完全按照错误消息所说的去做:
The direct answer is to do exactly as the error message says:
用括号代替
也就是说,用Fn(A, B)
真正的问题是您不允许实施Fn*
自己在稳定的 Rust 中的特性家族.
The real problem is that you are not allowed to implement the Fn*
family of traits yourself in stable Rust.
您提出的真正问题更难确定,因为您没有提供MCVE,因此我们减少了猜测.我会说你应该反过来说;创建一个新特征,为闭包和您的类型实现它:
The real question you are asking is harder to be sure of because you haven't provided a MCVE, so we are reduced to guessing. I'd say you should flip it around the other way; create a new trait, implement it for closures and your type:
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() {}
这篇关于我如何解决错误“'Fn'-family traits'类型参数的精确格式可能会发生变化"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!