![](/img/trans.png)
[英]How to make a Rust Generic Struct/Trait require a Box<other trait>?
[英]How to restrict generic implementation of a trait in Rust?
作為學習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,它能夠改變其BaseType
實現Rand
每個HasVectorGenome
(為了能夠生成一個新的隨機值)。 就像是:
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
,我無法編譯。 我不知道如何正確表達這一點。
我已經在操場上放置了這個代碼的完整工作版本(除了我刪除了隨機部分)。
首先,我從HasVectorGenome
刪除了IndividualType
參數。 這只是實現特征的類型,並且您對特征的定義與此不一致( new_from_vec
返回IndividualType
但get_vec
消耗Self
)。
其次,我將BaseType
關聯類型,這意味着任何單個類型都有一個唯一的基本類型。 這在技術上是一種限制,但在大多數情況下,你不需要靈活性,它使類型更簡單(實際上是擺脫你所看到的錯誤所需的主要變化)。 所以現在的特點是:
pub trait HasVectorGenome {
type BaseType;
fn new_from_vec(genome: Vec<Self::BaseType>) -> Self;
fn get_vec(&self) -> Vec<Self::BaseType>;
}
然后,我調整了GeneralMutator
實現的where子句:
impl<T> Mutator<T> for GeneralMutator
where T: HasVectorGenome,
T::BaseType : Rand
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.