必须指定哪个通用参数?
问题描述:
我遇到了一个问题,我有这样的特质(有些东西略):必须指定哪个通用参数?
use rand::Rng;
pub trait GeneticAlgorithm<R, Ins, C> : Clone where R: Rng {
fn call<F>(&self, program: F) where F: FnOnce(&C);
}
此结构实现的特点:
pub struct Mep<Ins> {
instructions: Vec<Ins>,
unit_mutate_size: usize,
crossover_points: usize,
}
impl<R, Ins> GeneticAlgorithm<R, Ins, Vec<Ins>> for Mep<Ins> where R: Rng, Ins: Clone {
fn call<F>(&self, program: F) where F: FnOnce(&Vec<Ins>) {
program(&self.instructions);
}
}
在测试中,我尝试运行此:
let mut rng = Isaac64Rng::from_seed(&[1, 2, 3, 4]);
let (a, b) = {
let mut clos = || Mep::new(3, 3, rng.gen_iter::<u32>().map(|x| x % 10).take(10));
(clos(), clos())
};
let mut c = Mep::mate((&a, &b), &mut rng);
c.call(|x: &Vec<u32>| panic!());
Rust声称它不能在某处推断某种类型,但我不知道如何指定闭包的类型(如果是问题),也不能确定它们h特定的通用参数导致问题:
error: unable to infer enough type information about `_`; type annotations or generic parameter binding required [E0282]
c.call(|x: &Vec<u32>| panic!());
需要指定哪个通用参数?
如果有人想构建代码本身,我是hosting it on GitHub。
答
让我们看看你的宣言,修剪了一下为清楚:
pub trait GeneticAlgorithm<R, Ins, C> {
fn call<F>(&self, program: F);
}
有4种泛型类型在这里:R
,Ins
,C
和F
。现在,让我们看看你的实现(再次修整):
impl<R, Ins> GeneticAlgorithm<R, Ins, Vec<Ins>> for Mep<Ins> {
fn call<F>(&self, program: F);
}
所以,你现在C
取决于Ins
提供一个具体的数值。您仍然有3个用户必须指定的参数:Ins
,F
和R
。
F
将根据封闭类型调用函数时指定。将在Mep
结构创建时指定Ins
。
那留下R
。 根据这些声明,R
应该是什么?这是不可能的。这似乎只是您实施中的错误;很可能你应该把它放在某个地方。另一种选择是你只需要一个你不需要的参数。