I'm new to rust with experience with Java, C++, and Python. In order to get more familiar with Rust I need to learn how to think more like a crab (rustecean?). At uni, OOP was the major method of programming taught, Rust only has inheritance of traits, not structs.
The most useful thing in inheritance, I find is field inheritance, but that doesn't exist in Rust (at least not to my knowledge). Is there any good material on how to write good, clean code without that? Most of what I find is just proselytizing "composition over inheritance", but I don't care about dogmatic discussion in programming as everything has its place.
The obvious and (IMO) very ugly OOP workaround would be defining traits with methods that look like fields e.g
class Device:
wattage: float
name: str
fs_path: str # /dev/...
class AudioDevice(Device):
sample_rate: float
volume: float
class Microphone(AudioDevice):
directional: bool
class SoundSystem(AudioDevice):
speaker_count: int
bass_count: int
trait HasDeviceProperties {
fn wattage(&self) -> f32;
fn name(&self) -> String;
fn fs_path(&self) -> String;
}
trait HasAudio: HasDeviceProperties {
fn sample_rate(&self) -> f32;
fn volume(&self) -> f32;
}
trait RecordsAudio: HasAudio {
fn directional(&self) -> bool;
}
trait PlaysAudio: HasAudio {
fn speaker_count(&self) -> u8;
fn bass_count(&self) -> u8;
}
struct Microphone {
_wattage: f32,
_name: String,
_fs_path: String,
_sample_rate: f32,
_volume: f32,
_directional: bool,
}
impl RecordsAudio for Microphone {
fn wattage(&self) -> f32 { self._wattage }
fn name(&self) -> String { self.name }
// ...
}
// Repeat for SoundSystem and replace directional with the other methods
I haven't run this through the compiler yet, but it should look similar to this. It is in the Rust by Example: Supertraits chapter, but this can't be the compositional or rust way of doing it (at least I hope it isn't). There'd be loads of copy-pasting and boilerplate code (maybe a macro could get rid of it, but ugh) and methods look like properties.
What's a conceptually better way of solving problems like this?