2
\$\begingroup\$

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?

\$\endgroup\$
7
  • 1
    \$\begingroup\$ Can you expand on what you mean by "looks a bit ugly"? Ugliness is not a universally shared concept. \$\endgroup\$ Commented Apr 17, 2018 at 17:04
  • 1
    \$\begingroup\$ @Shepmaster It's ugly for me as a newcomer to rust, practically, not in a way that rust is ugly, but how I've done it =) But I can't really say how it should look in a better implementation. I guess by "ugly" I mean I'm not quite sure it's idiomatic enough. \$\endgroup\$ Commented Apr 17, 2018 at 17:09
  • 1
    \$\begingroup\$ Just a little question: why is Config generic? \$\endgroup\$ Commented Apr 18, 2018 at 7:40
  • 1
    \$\begingroup\$ Not a full answer to the question, but a couple of stylistic tweaks you might like - you can replace the self.handlers.iter() in your for loop with &self.handlers (as &Vec<T> implements IntoIterator<&T>) , and you can drop the braces from structs with no fields. \$\endgroup\$ Commented Apr 18, 2018 at 15:38
  • 1
    \$\begingroup\$ You probably meant to use writeln!(f, ...)?; in your Debug impl instead of println!(...);. \$\endgroup\$ Commented Apr 19, 2018 at 2:08

0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.