[Solved] Implementing related traits in an abstract way

#1

Hello!

I’m trying to achieve the following: I want to implement several Audio backends (OpenAL, FMOD, …) and switch between those at program launch. Each backend has its own way of storing data about sound samples being played. OpenAL (or rather Alto) for instance stores alto::Buffer and additionally, in case the sample is currently playing, alto::StaticSource. FMOD uses completely different types. This gives a relationship between sample and backend.
In the code below, I tried to model this relationship by using associated types:

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

The error I get when I try to pass the Audio backend inside helper structs is:

error[E0308]: mismatched types
  --> src/main.rs:59:28
   |
59 |         self.entity.update(&mut self.backend);
   |                            ^^^^^^^^^^^^^^^^^ expected associated type, found type parameter
   |
   = note: expected type `&mut <<T as AudioBackend>::AudioBackendEntityData as AudioEntityData>::AudioBackend`
              found type `&mut T`

How can I solve this? Is there a better, more idiomatic way to achieve what I want to have in Rust?

Thanks,
Tyrant

0 Likes

#2

The thing that was missing was a constraint on the associated type in AudioBackend. Here is a working version:

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

0 Likes

closed #3

This topic was automatically closed after 27 hours. New replies are no longer allowed.

0 Likes