4

I would like to know how to have the struct Interface as a field in another struct when there is a type argument.

pub struct Interface<'a, 'b, 'c, DeviceT: Device + 'a> {}

pub struct Foo {
    iface: Interface<'static, 'static, 'static, Device + 'static>,
}

pub trait Device {
    type RxBuffer: AsRef<[u8]>;
    type TxBuffer: AsRef<[u8]> + AsMut<[u8]>;
}

This results in the error:

error[E0191]: the value of the associated type `TxBuffer` (from the trait `Device`) must be specified
 --> src/main.rs:4:49
  |
4 |     iface: Interface<'static, 'static, 'static, Device + 'static>,
  |                                                 ^^^^^^^^^^^^^^^^ missing associated type `TxBuffer` value

error[E0191]: the value of the associated type `RxBuffer` (from the trait `Device`) must be specified
 --> src/main.rs:4:49
  |
4 |     iface: Interface<'static, 'static, 'static, Device + 'static>,
  |                                                 ^^^^^^^^^^^^^^^^ missing associated type `RxBuffer` value

What is the correct way of having interface inside Foo?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Dragonight
  • 1,033
  • 2
  • 10
  • 20
  • Possible duplicate of [Why must the associated type be specified in a collection of references to types implementing a trait?](https://stackoverflow.com/questions/50905324/why-must-the-associated-type-be-specified-in-a-collection-of-references-to-types) – trent Oct 14 '18 at 12:59

1 Answers1

2

Your issue is that Device + 'static is not a type, but a bound, so you can't use it as a type argument. You can parameterise the struct with a type parameter that fulfills the bound:

pub struct Foo<D : Device + 'static> {
    iface: Interface<'static, 'static, 'static, D>,  
}

I don't think the compiler will allow for the kind of erasure you might be looking for - consider if we had similar code:

trait Foo<A> {
    fn get_a() -> A;
}

struct Bar {
    foo: Box<Foo<A>>,
}

// How would the compiler describe this type?
let a: ??? = some_bar.foo.get_a();
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Isaac van Bakel
  • 1,772
  • 10
  • 22