Skip to content

Instantly share code, notes, and snippets.

@flukejones
Forked from MCluck90/inheritance.rs
Last active February 21, 2019 21:40
Show Gist options
  • Save flukejones/7eeec917694e4fc5a60259c5bfdc4250 to your computer and use it in GitHub Desktop.
Save flukejones/7eeec917694e4fc5a60259c5bfdc4250 to your computer and use it in GitHub Desktop.
Inheritance-like problem in Rust
/// 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