pub trait IO {}
impl IO for f64 {}
pub trait Unit<Input: IO, Output: IO> {
fn process(&self, t: Option<Input>) -> Option<Output>;
}
pub struct UnitA;
impl Unit<f64, f64> for UnitA {
fn process(&self, t: Option<f64>) -> Option<f64> {
t /* this is just so compilator won't complain */
}
}
impl UnitA {
pub fn new() -> UnitA {
UnitA { }
}
}
pub struct UnitB;
impl Unit<f64, f64> for UnitB {
fn process(&self, t: Option<f64>) -> Option<f64> {
t /* this is just so compilator won't complain */
}
}
impl UnitB {
pub fn new() -> UnitB {
UnitB { }
}
}
fn main() {
/* trial example */
let units: Vec<Box<dyn Unit<dyn IO, dyn IO>>> = vec![
Box::new(UnitA::new()), /* <= this does not work */
Box::new(UnitB::new()), /* <= this does not work */
];
}
Hello everyone
(link to playground with exact same code)
I am trying to understand exactly how trait objects and generics work together, but I feel like I am missing a major piece. About 'dyn' exactly.
In this example, I am trying to build a Vec of trait objects that are safe objects, using different types of struct (UnitA, UnitB) that both implement the same generic trait object (Unit<IO, IO>).
As UnitA
or UnitB
would fit the dyn Unit
, I naively thought impl IO for f64
would have fit the dyn IO
generic requirement. But compiler isn't content:
--> src/main.rs:36:9
|
36 | Box::new(UnitB::new()),
| ^^^^^^^^^^^^^^^^^^^^^^ the trait `Unit<dyn IO, dyn IO>` is not implemented for `UnitB`
|
= help: the following implementations were found:
<UnitB as Unit<f64, f64>>
I understand this error, but I am not sure how to satisfy the compiler about the dyn IO
requirement.
What should I do differently for the compiler to be happy?
Does that mean that only concrete type, in place of dyn IO
, must be passed to Unit<>
of the Vec declaration for the compiler to be able to build a functional vector?
Thanks a lot for your time!