'How to deal with trait types?
I come from JVM world and I'm struggling with dealing with the traits. My goal is to provide an interface (that what it would be called in Java) that would represent the time provider, so I could use 'real' implementation in production environment and 'fake' in the tests, so I could stub the time.
In Java I'd have
interface Clock {
Instant now();
}
class UtcClock implements Clock {
Instant now() {
return Instant.now();
}
}
and then I could use Clock type as any other type.
In Rust I have
pub trait Clock {
fn now(&self) -> DateTime<Utc>;
}
pub struct UtcClock;
impl Clock for UtcClock {
fn now(&self) -> DateTime<Utc> {
return Utc::now();
}
}
However to be able to use dynamic type Clock in Rust and to move it between threads I have to used boxed type e.g. Arc<dyn Clock + Send + Sync> which wouldn't be required if I'd use concrete type UtcClock.
Is provided solution of using traits idiomatic in Rust? Or there are other techniques to decouple the 'interface' and the implementation?
If it is OK then is there any way to make it look better than Arc<dyn Clock + Send + Sync>?
Solution 1:[1]
Arc<dyn Clock + Send + Sync> seems likely to be best, unless you're able to use &dyn Clock + Send + Sync. You can then use an alias type to make it look better, e.g. type DynClock = Arc<dyn Clock + Send + Sync>;. See the Rust book and the reference.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Solomon Ucko |
