2

I want to play waves generated by the waver crate via the rodio crate. To generate waves, waver provides the WaveIterator struct. To play sound, rodio provides the OutputStreamHandle, which takes a Source. Source is a trait, which can be implemented, so my genius plan was to just take WaveIterator and let it implement Source.

But my plan was foiled, because I can't implement traits for structs from other classes. Not to worry, I found something called the newtype pattern, which wraps a struct, in my case WaveIterator in another struct, and I can implement Source for that.

But now the compiler complains, that my struct is not an iterator, because Source expects an iterator. I thought, maybe implementing Deref and DerefMut would solve that problem, but it didn't. Has it maybe something to do with the lifetime annotation of WaveIterator?

So what do I do now? I don't want to reimplement every trait from WaveIterator manually for my wrapper struct. Is there a way to "inherit" the traits from the wrapped struct? Or am I doing this completely wrong?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Modi57
  • 205
  • 1
  • 10
  • 3
    Prefer showing the code that you have so far and reproduces the problem. Also, considering that you already implemented `Source`, what stopped you from implementing `Iterator`? – E_net4 Jan 13 '22 at 16:29
  • Yeah, I just did that. But it doesn't feel that elegant – Modi57 Jan 13 '22 at 16:55
  • 2
    Implementing all the necessary traits on the newtype is the idiomatic way. One can also use a derive macro crate such as [`newtype-derive-2018`](https://crates.io/crates/newtype-derive-2018) or [`newtype-ops`](https://crates.io/crates/newtype-ops) to reduce the boilerplate. – E_net4 Jan 13 '22 at 17:35
  • 1
    @E_net4ismydisplayname Agreed, see also: [RFC 2393: Delegation](https://github.com/rust-lang/rfcs/pull/2393) (backlogged as of now). – Coder-256 Jan 13 '22 at 17:53

0 Answers0