Why is an explicit type needed in order to make this compile? I'd expect the compiler to understand that Box<STest>
is equal to Box<(dyn TTest + 'static)>
in the first test case since STest
implements the TTest
trait. What makes the compiler able to implicitly cast it to a BoxedTTest
in the second case, while it doesn't do so in the first case?
I'm compiling it with rustc --edition 2018 mwe.rs
on rustc 1.40.0
(stable), but the same error happens with --edition 2015
and on rustc 1.42.0-nightly
.
trait TTest {}
struct STest {}
impl TTest for STest {}
type BoxedTTest = Box<dyn TTest>;
fn foo(_test: &BoxedTTest) {}
pub fn main() {
// expected trait TTest, found struct `STest`
let test1 = Box::new(STest {});
foo(&test1);
// OK
let test2: BoxedTTest = Box::new(STest {});
foo(&test2);
}
The full error is as follows:
error[E0308]: mismatched types
--> mwe.rs:13:9
|
13 | foo(&test1);
| ^^^^^^ expected trait TTest, found struct `STest`
|
= note: expected type `&std::boxed::Box<(dyn TTest + 'static)>`
found type `&std::boxed::Box<STest>`