-
-
Save flukejones/7eeec917694e4fc5a60259c5bfdc4250 to your computer and use it in GitHub Desktop.
Inheritance-like problem in Rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// Problem: there is a lot of duplication in function implementations. | |
/// The two types should have the same interface but use a different underlying type. | |
/// | |
/// How can I reduce the amount of duplication and avoid having to update the code in two places? | |
/// In other languages, I would define a base class which accepts a generic type for the `SoundSource`s | |
/// but I don't know how to solve this sort of problem in Rust. | |
struct Sound { | |
// Shared properties | |
is_playing: bool, | |
// Sort of shared | |
source: Option<SoundSource>, | |
spatial: Option<SpatialSoundSource>, | |
} | |
impl Sound { | |
fn play(&mut self) { | |
self.stop(); | |
self.play_later(); | |
} | |
fn stop(&mut self) { | |
if let Some(source) = self.source { | |
source = SoundSource::new(); | |
} | |
if let Some(spatial) = self.spatial { | |
source = SpatialSoundSource::new(); | |
} | |
self.is_playing = false; | |
} | |
fn play_later(&mut self) { | |
if let Some(spatial) = self.spatial { | |
source.reset_position(); | |
} | |
self.source.play_later(); | |
self.is_playing = true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment