Skip to content

Instantly share code, notes, and snippets.

@MCluck90
Last active February 21, 2019 21:39
Show Gist options
  • Save MCluck90/994ec624aab5e18e4ee16b48da131f16 to your computer and use it in GitHub Desktop.
Save MCluck90/994ec624aab5e18e4ee16b48da131f16 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: SoundSource,
}
struct SpatialSound {
// Shared properties
is_playing: bool,
// Sort of shared (is a superset of SoundSource in terms of interface)
source: SpatialSoundSource,
}
impl Sound {
fn play(&mut self) {
self.stop();
self.play_later();
}
fn stop(&mut self) {
self.source = SoundSource::new();
self.is_playing = false;
}
fn play_later(&mut self) {
self.source.play_later();
self.is_playing = true;
}
}
impl SpatialSound {
// Duplicate of Sound::play
fn play(&mut self) {
self.stop();
self.play_later();
}
// Duplicate of Sound::stop but with a different type
fn stop(&mut self) {
self.source = SpatialSoundSource::new();
self.is_playing = false;
}
// Mostly duplicate of Sound::play_later
fn play_later(&mut self) {
self.source.reset_position(); // Here's how it differs
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