TL;DR: Is it possible to add functions to a trait, and then not have to re-implement all functions for the implementation? I assume I'm totally missing how to do it rust-y, so here is the longer explanation:
Longer version:
I'm trying to de-Python my brain and it's going okay. I'm doing a XML parser where I "hand off" the processing of certain parts of the document to different modules/classes. Sample XML:
<xml>
<car>
<name>First car</name>
<brand>Volvo</brand>
</car>
<plane>
<name>First plane</name>
<brand>Boeing</brand>
</plane>
<car>
<name>Second car</name>
<brand>Volvo</brand>
</car>
</xml>
In reality it's much more complex and about 500-1000MB in size.
Using quick-xml I then do:
Ok(Event::Start(ref e)) => {
match e.name() {
b"car" => car::Car::process(&mut reader, event);
b"plane" => plane::Plane::process(&mut reader, event);
_ => return Err("Unexpected Tag"),
}
},
Now this works, and Car for example is a struct with an implementation. However, in reality Car and Plane is actually pretty similar so I want to re-use the core "xml processing logic" between them, similar to having a base class in Python.
My first attempt was:
trait Vehicle {
fn process(reader: &mut Reader<BufReader<File>>, event: &quick_xml::events::BytesStart) {
...
self.handle_something(...) // this obviously doesn't work
....
}
}
struct Car {
name: String,
brand: String,
}
impl Vehicle for Car { // won't compile since I'm not implementing the process function
fn handle_something() {
}
}
So I'm trying to keep the base function (process) the same in both Car and Plane, and have that base function hand over to a function (handle_something) which I do override.
In Python I would do:
class Vehicle() {
def process() {
...
self.handle_something()
..
}
}
class Car(Vehicle) {
def handle_something() {
...
}
}
And it would inherit the process function from Vehicle
Obviously I'm missing something, but despite spending a few hours on this (and reading the rust-lang book - which is awesome! and stack overflow and blog posts) I'm not wrapping my head around how I would do this.
Any helpers would be greatly appreciated ![]()