Denis Steinman
Denis Steinman

Reputation: 7809

How to deduce sub generic types from main generic type?

Is it possible to change this code to specify just the main type: impl Writer<MyTable> and let Rust deduce the H and R parameters automatically?

trait Table<H, R> {
    fn rows(&self) -> &Vec<R>;
    fn header(&self) -> &H;
}

// MyTable implements Table

trait Writer<H, R, T: Table<H, R>> {}

impl Writer<MyTableHeader, MyTableRow, MyTable> for WriterImpl {}

Upvotes: 0

Views: 130

Answers (1)

Sunreef
Sunreef

Reputation: 4552

One way to solve your problem would be to move the H and R template parameters into the Table trait as associated types:

trait Table {
    type Header;
    type Row;

    fn rows(&self) -> &Vec<Self::Row>;
    fn header(&self) -> &Self::Header;
}

When implementing this trait, you specify which type to use as Header and Row.

You can then modify your Writer to accept only one template parameter:

trait Writer<T: Table> {}

Upvotes: 4

Related Questions