How to fix the error: `conflicting implementations of trait`?

I'm trying to organize my code like in this playground: Rust Playground.

Is there a way to avoid that error:

Compiling playground v0.0.1 (/playground)
error[E0119]: conflicting implementations of trait `trait_declaration::Repo` for type `usage::Database`
  --> src/main.rs:28:9
   |
17 |         impl crate::trait_declaration::Repo for Database {
   |         ------------------------------------------------ first implementation here
...
28 |         impl crate::trait_declaration::Repo for Database {
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `usage::Database`

For more information about this error, try `rustc --explain E0119`.

The async-graphql's team resolved this issue using #[derive(MergedObject)].

Is there a way I can fix this?

A macro?

I'm new to Rust... be kind to me! :smile:

You are literally trying to implement the same trait for the same type twice. That's not going to work. You can avoid the error by not doing that.

A trait implementation has to be fully contained in a single impl block. Like this:

mod trait_declaration {
    #[async_trait::async_trait]
    pub trait Repo: Send + Sync {
        async fn coach_by_id(&self, id: u64) -> String;

        async fn player_by_id(&self, id: u64) -> String;
    }
}

mod usage {
    struct Database;

    #[async_trait::async_trait]
    impl crate::trait_declaration::Repo for Database {
        async fn coach_by_id(&self, _id: u64) -> String {
            "coach_by_id here".to_string()
        }

        async fn player_by_id(&self, _id: u64) -> String {
            "player_by_id here".to_string()
        }
    }
}

#[tokio::main]
async fn main() {
    println!("Hello world");
}

1 Like