我有lib.rs:
pub mod genetics {
use std;
pub trait RandNewable {
fn new() -> Self;
}
pub trait Gene : std::fmt::Debug + Copy + Clone + RandNewable {}
#[derive(Debug, Copy, Clone)]
pub struct TraderGene {
cheat: bool,
}
impl RandNewable for TraderGene {
fn new() -> TraderGene {
TraderGene {
cheat: true,
}
}
}
#[derive(Debug)]
pub struct DNA<G: Gene> {
genes: [G; 3],
}
impl <G: Gene> DNA<G> {
pub fn create() -> DNA<G> {
DNA {
genes: [RandNewable::new(), RandNewable::new(), RandNewable::new()],
}
}
pub fn mutate(&self) -> DNA<G> {
let mut copy = self.genes;
copy[0] = RandNewable::new();
DNA {
genes: copy,
}
}
}
}
我正在尝试使用main.rs中的定义:
extern crate trafficgame;
use trafficgame::genetics::{DNA, TraderGene, Gene, RandNewable};
fn main() {
let t1: DNA<TraderGene> = DNA::create();
let t2 = t1.mutate();
}
但是我遇到两个错误:
the trait `trafficgame::genetics::Gene` is not implemented for the type `trafficgame::genetics::TraderGene
和
type `trafficgame::genetics::DNA<trafficgame::genetics::TraderGene>` does not implement any method in scope named `mutate`
TraderGene
肯定会实现Gene
特征,但似乎RandNewable
的impl不在main范围内。另一个问题是,由于mutate未在特征中声明,我不知道在main中导入什么以引用mutate。我是否错误地组织了事情?
答案 0 :(得分:5)
即使您的Gene
特征没有方法,TraderGene
也不会自动实现它,即使它实现了所有Gene
的超级特征。您必须在impl
模块中写一个空的genetics
:
impl Gene for TraderGene {}