I want to implement an application that has different backends for querying data from various sources. All these backends are implemented BackendTrait
trait. These backends are created during the initialising time, and I want to store them in a vector.
Two options are available: using trait object or enum.
I always find trait objects to be heavy and not entirely aligned with Rust's philosophy. However, by using enum, each time I want to invoke trait method of a type, I need to match
it first, then I can call the trait function.
For example, I have struct Rsync
and struct Ftp
backends, and all of them are implemented BackendTrait
:
trait BackendTrait {
fn upload();
}
Then I have this enum:
enum Backend {
FTP(Ftp),
RSYNC(Rsync),
}
These two backends are stored in a vector like this:
let ftp = Ftp{};
let rsync = Rsync{};
let backends = vec![Backend(ftp), Backend(rsync)];
Then, call upload()
function for each of these backends:
for b in backends.iter() {
match b {
FTP(b) => b.upload(),
RSYNC(b) => b.upload(),
}
}
The mach{}
here looks verbose here.
It is good to use trait object replace enum here?
Or, there are some magic ways to remove the match{}
clause,