For writing a very large program, I see no way to alleviate having to write the same code for each struct that uses a certain shared behaviour.
For example, Dog may "bark":
struct Dog {
is_barking: bool,
....
}
impl Dog {
pub fn bark(self) {
self.is_barking = true;
emit_sound("b");
emit_sound("a");
emit_sound("r");
emit_sound("k");
self.is_barking = false;
}
....
}
And many breeds of this dog may exist:
struct Poodle {
unique_poodle_val: &str
}
impl Poodle {
pub fn unique_behaviour(self) {
self.some_behaviour();
}
}
struct Rottweiler {
unique_rottweiler_val: u32
}
impl Rottweiler{
pub fn unique_behaviour(self) {
self.some_behaviour();
}
}
The issue is that Rust seems incapable of this in my current knowledge, but it needs to be done and I need a workaround for:
- Allowing Poodle and Rottweiler to bark using the exact same behavior which the breeds should not need to regard.
- Allowing this to be possible without recoding bark() in every breed module, which is programming hell as it leads to repetitious code and every module has to implement bark().
- Traits are the inverse and cannot access the struct, so default-trait implements do not work. Rust does not support OOP-like inheritance and nor is it desired here.
Therefore, I ask: How would it be possible to implement bark() without rewriting bark() in each module, since Poodle and Rottweiler bark exactly the same way after all?
Please provide an example of how to solve this issue in Rust code, idiomatic and slightly hacky solutions are welcome but please state which they are as I am still learning Rust. Thank you.
Edit: The boolean is not a thread thing, rather it's a example of setting some state before doing something, i.e. emit_sound is within this state. Any code we put into bark() has the same issue. It's the access to the struct variables that is impossible with say, traits.
DogandPoodle/Rottweiler. Do you want each breed to contain aDog? Do you wantDogto have abreedthat is a tagged union? Something else? - BergiPoodlemust be a struct" and "barkmust be a method". Again, requirements and constraints: what does this program do besides demonstrate a bad design? - trentclbarkthe way she does because she is aPoodle, but because she has aVoiceBoxwhich is of a particular shape and size and also has aBarkingBehaviorthat she learned from other dogs.Poodleis an idea purely in the minds of some humans who find it easier to understand nature by pretending that sharp dividing lines exist where, in reality, none do. - trentcl