【发布时间】:2015-06-07 21:18:57
【问题描述】:
我有 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 没有在 trait 中声明,我不知道在 main 中导入什么来引用 mutate。我是不是组织错了?
【问题讨论】:
-
仅供参考,Rust 样式是 4 空格缩进。
标签: rust