I've implemented a simple polymorphic structure, which looks a bit ugly and I'm afraid I am missing an idiomatic way of doing it.
To describe briefly what I'm trying to achieve here: I would like to have a structure with a collection of handlers, which all must implement specific trait.
use std::fmt;
use std::fmt::Formatter;
use std::fmt::Error;
trait Handler {
fn get_type(&self) -> String;
}
struct FileHandler {
}
struct DbHandler {
}
impl Handler for FileHandler {
fn get_type(&self) -> String {
"file".to_string()
}
}
impl Handler for DbHandler {
fn get_type(&self) -> String {
"db".to_string()
}
}
struct Config {
handlers: Vec<Box<Handler>>
}
impl fmt::Debug for Config {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
for h in self.handlers.iter() {
println!("{}", h.get_type());
}
write!(f, "config")
}
}
pub fn run() {
let mut handlers: Vec<Box<Handler>> = Vec::new();
let fh = FileHandler {};
let dh = DbHandler {};
handlers.push(Box::new(fh));
handlers.push(Box::new(dh));
let c = Config { handlers };
println!("{:?}", c);
}
Is there a way of more cleaner or more idiomatic solution here?
Configgeneric? \$\endgroup\$self.handlers.iter()in yourforloop with&self.handlers(as&Vec<T>implementsIntoIterator<&T>) , and you can drop the braces from structs with no fields. \$\endgroup\$writeln!(f, ...)?;in yourDebugimpl instead ofprintln!(...);. \$\endgroup\$