0

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 {}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Denis Sologub
  • 7,277
  • 11
  • 56
  • 123
  • 2
    On an aside note, consider returning `&[R]` instead of `&Vec`. The caller will be no worse off because they couldn't mutate the vector through a shared reference to begin with, and using a slice avoids hard-coding how the data is stored in the table (other than it being stored contiguously). Also, a slice has one less level of indirection when accessing the data because it contains the pointer to data, whereas a reference to the vector first has to access the vector, and only then the data. – user4815162342 Aug 19 '20 at 12:31
  • 2
    ^ That comment in more detail: [Why is it discouraged to accept a reference to a String (&String), Vec (&Vec), or Box (&Box) as a function argument?](https://stackoverflow.com/q/40006219/155423) – Shepmaster Aug 19 '20 at 13:38

1 Answers1

4

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> {}
Sunreef
  • 4,452
  • 21
  • 33