I am having trouble understanding the following error:
// test.rs
struct A {
a: u32
}
trait B { }
impl B for A { }
struct C {
c: Vec<Box<dyn B>>,
}
fn test() {
let a = A {a: 1};
let a_vec = vec![Box::new(a)];
let c = C {
c: a_vec,
// c: vec![Box::new(a)],
};
}
Compile error:
mismatched types
expected trait object `dyn test::B`, found struct `test::A`
The error occurs on the line where I try to create C. What's interesting is that if I create C in the following way then it compiles alright.
let c = C {
c: vec![Box::new(a)],
};
Another way that would work is
let a_vec: Vec<Box<dyn B>> = vec![Box::new(a)];
let c = C {
c: a_vec,
};
One other experiment I did is to change the type of C.c to just Box instead of Vec<Box>, and then it compiles no matter how I initiate it.
Seems to me this might be some missing feature/bug of Rust's type inference regarding vector of trait objects? I am still very new to Rust so any idea on this is really appreciated!
vec![Box::new(a) as _]. The error itself is due to the difference between the thin pointer (boxed concrete struct) and a fat pointer (boxed dyn trait). One is convertible to the other (provided the struct implements the trait), but sometimes the compiler needs some nudging to perform the conversion. Whether that's a deficiency in the type inference or a consequence of some deeper principle is a good question. - user4815162342