1

I'd like to implement my own version of a Rust standard library feature and use my version and the real standard library version interchangeably.

If the standard library feature were a trait, this would be easy. However, the standard library feature (in this case, std::sync::Condvar) is implemented as

pub struct Condvar {...}

impl Condvar {...}

I tried doing

impl Condvar for MyCondvar {...}

but got an error ("error[E0404]: expected trait, found struct Condvar")

How should I do this? I've also tried

pub trait CondvarTrait { // copy entire interface of Condvar }

impl CondvarTrait for Condvar {
  // copy entire interface of Condvar again,
  // implementing foo(&self, ...) by calling self.foo(...)
}

impl CondvarTrait for MyCondvar { // my own implementation }

which compiles, but is super verbose. Is there a better way?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Greg Owen
  • 947
  • 8
  • 19
  • Just an idea: make two versions of your library. One defines your types. The other just re-exports the standard types. – Sebastian Redl Jul 24 '19 at 12:28
  • I think, without new Rust features or some macro magic, the latter example is the only way to do it. There's no way to turn a struct into a trait. – Joe Clay Jul 24 '19 at 12:29

1 Answers1

3

You need to copy the entire interface of the type and reimplement it by calling the inherent methods.

See also:

Is there a better way?

Not with how you've described the requirements.

That being said, you aren't introducing any abstraction suited to your domain. In many cases, you don't want the full power of the underlying type(s), but want to do some higher-level abstraction. If you create that abstraction as a trait, then you can implement the new trait for any useful types.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366