【发布时间】:2016-06-02 05:14:43
【问题描述】:
作为学习 Rust 的借口,我正在编写遗传算法的代码,以及稍后的遗传编程。
我为变异操作声明了一个特征:
pub trait Mutator<IndvidualType> {
fn mutate(&self, individual: &IndvidualType) -> IndvidualType;
}
为每个IndividualType 实现特征很容易,但我想要更通用的特征,每个列表(向量)类型基因组都通用的特征,例如:
pub trait HasVectorGenome<IndividualType, BaseType> {
fn new_from_vec(genome: Vec<BaseType>) -> IndvidualType;
fn get_vec(&self) -> Vec<BaseType>;
}
我希望有一个通用的mutator,它能够改变每个HasVectorGenome 的BaseType 实现Rand(以便能够生成新的随机值)。比如:
struct GeneralMutator;
impl<B, T> Mutator<T> for GeneralMutator
where T: HasVectorGenome<T, B>,
B: Rand
{
fn mutate(&self, individual: &T) -> T {
let genome: Vec<B> = individual.get_vec();
genome[0] = rand::random::<B>();
T::new_from_vec(genome)
}
}
我收到错误the type parameter `B` is not constrained by the impl trait, self type, or predicates,我无法编译。我不知道如何正确表达。
【问题讨论】: