【问题标题】:Using a no-method trait implementation in a different module在不同的模块中使用无方法特征实现
【发布时间】: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


【解决方案1】:

即使你的Gene trait 没有方法,TraderGene 也不会自动实现它,即使它实现了Gene 的所有超特征。你必须在genetics 模块中写一个空的impl

impl Gene for TraderGene {}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    • 2022-11-02
    • 1970-01-01
    • 2013-10-31
    • 1970-01-01
    • 2019-04-04
    相关资源
    最近更新 更多