Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysterious conflicting implementations

Tags:

I was trying to test my code with fixed time. so I wrote something like this:

use std::time::{SystemTime, UNIX_EPOCH};

trait Clock {
    fn now(&self) -> SystemTime;
}

trait MixInClock {
    type Impl;
}

struct RealClock;
impl<T: MixInClock<Impl = RealClock>> Clock for T {
    fn now(&self) -> SystemTime {
        SystemTime::now()
    }
}

struct FakeClock;
impl <T: MixInClock<Impl = FakeClock>> Clock for T {
    fn now(&self) -> SystemTime {
        UNIX_EPOCH
    }
}

struct DIContainer;
impl MixInClock for DIContainer {
    type Impl = FakeClock;
}

This code gives me an error:


error[E0119]: conflicting implementations of trait `Clock`:
  --> src/lib.rs:19:1
   |
12 | impl<T: MixInClock<Impl = RealClock>> Clock for T {
   | ------------------------------------------------- first implementation here
...
19 | impl <T: MixInClock<Impl = FakeClock>> Clock for T {
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation

Why? There's no possibility that T implements MixInClock<Impl = RealClock> and MixInClock<Impl = FakeClock> at same time. right?

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=95e3647b30ae0e37c45ac18da495a3c5

like image 339
tadosappo Avatar asked Mar 07 '20 23:03

tadosappo


1 Answers

You ran into a long-standing issue with Rust's coherence rules. There are proposals how to resolve this, but the work has been postponed for now. Quoting Jonas Schievink's most recent comment on the bug:

To give an update on this: In 2016, RFC 1672 was proposed to fix this, but was postponed until the Chalk integration is done. Additionally, according to rust-lang/rfcs#1672 (comment), allowing these kinds of impls would allow users to express mutually exclusive traits, which is a very powerful feature that needs more in-depth consideration by the language team (hence marking as blocked on an RFC as well).

like image 133
Sven Marnach Avatar answered Oct 11 '22 17:10

Sven Marnach