我试图使用impl来处理一些奇怪的类型逻辑。这是一个快速重建的错误:
trait Schrodingers {}
struct AliveCat;
impl Schrodingers for Container<AliveCat> {}
struct DeadCat;
impl Schrodingers for Container<DeadCat> {}
struct Container<Cat1>
where Container<Cat1>: Schrodingers
{
cat: Cat1,
}
impl<Cat2> Container<Cat2>
where Container<Cat2>: Schrodingers
{
fn dead_cat() -> Container<DeadCat> {
let observed_cat = DeadCat;
Container { cat: observed_cat }
}
fn alive_cat() -> Container<AliveCat> {
let observed_cat = AliveCat;
Container { cat: observed_cat }
}
}
fn main() {
let dead_cat = Container::dead_cat();
let alive_cat = Container::alive_cat();
}
导致编译器错误:
error[E0308]: mismatched types
--> src/main.rs:19:26
|
19 | Container { cat: observed_cat }
| ^^^^^^^^^^^^ expected type parameter, found struct `DeadCat`
|
= note: expected type `Cat2`
= note: found type `DeadCat`
error[E0308]: mismatched types
--> src/main.rs:19:9
|
19 | Container { cat: observed_cat }
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `DeadCat`, found type parameter
|
= note: expected type `Container<DeadCat>`
= note: found type `Container<Cat2>`
error[E0308]: mismatched types
--> src/main.rs:24:26
|
24 | Container { cat: observed_cat }
| ^^^^^^^^^^^^ expected type parameter, found struct `AliveCat`
|
= note: expected type `Cat2`
= note: found type `AliveCat`
error[E0308]: mismatched types
--> src/main.rs:24:9
|
24 | Container { cat: observed_cat }
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `AliveCat`, found type parameter
|
= note: expected type `Container<AliveCat>`
= note: found type `Container<Cat2>`
我已经能够使用其他方法解决这个问题了,但为什么编译器会发现这个令人困惑的问题呢?