Using a no-method trait implementation in a different module

538 views Asked by At

I have 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,
      }
    }
  }
}

and I'm trying to use the definitions in main.rs:

extern crate trafficgame;

use trafficgame::genetics::{DNA, TraderGene, Gene, RandNewable};

fn main() {
  let t1: DNA<TraderGene> = DNA::create();
  let t2 = t1.mutate();
}

but I'm getting two errors:

the trait `trafficgame::genetics::Gene` is not implemented for the type `trafficgame::genetics::TraderGene

and

type `trafficgame::genetics::DNA<trafficgame::genetics::TraderGene>` does not implement any method in scope named `mutate`

TraderGene definitely implements the Gene trait, but it seems like the impl for RandNewable isn't in scope in main. The other problem is that since mutate isn't declared in a trait, I don't know what to import in main in order to reference mutate. Am I organizing things incorrectly?

1

There are 1 answers

0
Francis Gagné On BEST ANSWER

Even though your Gene trait has no methods, TraderGene will not automatically implement it, even if it implements all of Gene's supertraits. You must write an empty impl in your genetics module:

impl Gene for TraderGene {}