Implementation of the add()
function is here: https://github.com/raldone01/python_lessons_py/blob/main/lib.py
Implementation of the add()
function is here: https://github.com/raldone01/python_lessons_py/blob/main/lib.py
In Rust, as far as I understand anyway, traits define shared behavior.
They’re certainly the concept closest to e.g. C#/Java interfaces. But you can also define shared behaviour with enums, as Rust’s enums are on steroids.
Basically, let’s say you’ve got two existing types TypeA
and TypeB
for which you want to define shared behaviour.
Then you can define an enum like so:
enum SharedBehaviour {
A(TypeA),
B(TypeB),
}
And then you can define the shared behavior with an impl
block on the enum:
impl SharedBehaviour {
pub fn greet(&self) {
match self {
SharedBehaviour::A(type_a) => println!("Hi there, {}!", type_a.name),
SharedBehaviour::B(type_b) => println!("Hello, {}!", type_b.metadata.forename),
}
}
}
On the flipside, Rust doesn’t have superclasses/inheritance for defining shared behaviour.
I feel like this has somewhat shifted in recent years. Due to type-aware IDEs/editors being pretty much universal now, having types speeds you up in that initial phase, too. And type inference eliminates much of the inertia, too.
What the hell? Is this the new “Microsoft ❤️
CancerOpen-Source” ?