On a philosophical level, traits tend to be a better solution than enums for continuously extending types (at least that's what I've heard). They also provide a nice polymorphism substitute for inheritance. But, on a performance level, are traits more expensive than enums?
fn main() {
let x = get_x();
x.foo();
}
Trait Solution:
trait Foo {
fn foo(&self);
}
struct A;
impl Foo for A {
fn foo(&self) {
println!("Doing A stuff...");
}
}
struct B;
impl Foo for B {
fn foo(&self) {
println!("Doing B stuff...");
}
}
fn get_x() -> impl Foo { A }
Enum Solution:
enum Foo {
A,
B,
}
impl Foo {
fn foo(&self) {
match self {
Self::A => println!("Doing A stuff..."),
Self::B => println!("Doing B stuff..."),
_ => println!("Not implemented yet"),
}
}
}
fn get_x() -> Foo { Foo::A }
With the trait solution I only have to implement its functions for a new type, but with the enum solution I have to add a variant, change the implementation itself, while always needing a "_" case to prevent breaking changes. Am I sacrificing any speed by preferring a trait design over an enum design?