Implying Generics

I have a struct like so:

pub struct Parser<P: ParseType, T: TextType> {
parser_templates: ParserTemplate<P>,
item_types: ItemTypes<T>
}

I am in the unfortunate situation where if P is set to some value, T will also be set to a similar value or vice verse:

Parser::<TextParser, TextItem>::new()

or

Parser::<HTMLParser, HTMLItem>::new()

Rather than refactor is there a way I can imply one based on the other? Or perhaps some sort of way to wrap like kinds? It would be nice to pass only one thing to the Parser creation.

Have you tried an associated type?

trait ParseType {
     type Item: ItemType;
}

pub struct Parser<P: ParseType> {
    parser_templates: ParserTemplate<P>,
    item_types: ItemTypes<P::Item>
}

Random aside: The idiomatic spelling in Rust is HtmlParser rather than HTMLParser.

2 Likes

Awesome that worked thanks!