Update
TL;DR: references to redirect:
Abstraction without overhead: traits in Rust
What makes something a “trait object”?
In C++, we can use class inheritance to implement interface polymorphism:
class Base {
public:
virtual void func(int) = 0;
};
class DerivedA : Base {
public:
void func(int) override {
// specific behavior of DerivedA
}
};
class DerivedB : Base {
public:
void func(int) override {
// specific behavior of DerivedB
}
};
But virtual functions come with some performance cost. Sometimes what concerned is the different behaviors of the same interface (the func
method in this example), and performance is preferred over dynamic dispatch. In these cases, Base
is used as a skeleton only. In C++, inheritance without virtual also works:
class Base {
public:
void func(int);
};
class DerivedA : Base {
public:
void func(int) {
// specific behavior of DerivedA
}
};
class DerivedB : Base {
public:
void func(int) {
// specific behavior of DerivedB
}
};
Is there something equivalent to this in Rust? I know traits in Rust are quite similar, but the use of trait
is always virtual. Dynamic dispatch is not necessary here.
Edit: Thank you all who give comments and criticisms. I misunderstand about trait
. Traits can be statically dispatched, and also can be dynamically dispatched, depending on your need.
This question was not described well at start, maybe it is more about "how to implement and use an interface, without dynamic dispatch in Rust". Personally I come from C++ background and I am reading Inside the C++ Object Model by Stanley B. Lippman recently. This question also proves that use the C++ thought directly into Rust is not a good method when consider trait, polymorphism features of Rust.