How to select which module impliments the trait

struct Array{}

trait Point{}

mod one{
    use crate::{Array,Point};
    impl Point for Array{}

mod two{
    use crate::{Array,Point};
    impl Point for Array{}

//how do i select which mod impliment the trait

The two sub-modules can't both implement it. There can only be one implementation.

Where best to put the implementation depends both on the situation and one's opinion, but if the struct and trait are defined in the same place, that's a logical place for the implementation too.

is there any logical way to implement a specific trait if there are 2 different implementation on same struct of same kind of trait??

No, there is at most one implementation of a given trait for a given type. It's a property called coherence.

Unless by "same kind of trait" you mean there might be two distinct traits, or a parameterized trait, etc.


The only things that control which trait implementation is selected are

  • the Self type
  • the trait
  • the generic parameters of the trait

But you can introduce a parameter to distinguish the implementations; for example:

struct Array {}

trait Point<const X: bool> {}

mod one {
    use crate::{Array, Point};
    impl Point<false> for Array {}
mod two {
    use crate::{Array, Point};
    impl Point<true> for Array {}
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.