我尝试使用一个实现来处理一些奇怪的类型逻辑。以下是该错误的快速重构:
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>`
我已经能够使用其他方法解决这个问题,但为什么编译器会感到困惑呢?
struct
自身上的where
子句删除可以使其正常工作,或者在alive_cat()
中加上限定词,例如Container::<AliveCat>
。我认为struct
/impl
的循环性质(两者都需要对方)导致了类型推断失败。 - Chris EmersonCat2
,并在单独的impl
块中实现Container<DeadCat>
和Container<AliveCat>
。但确实,推断失败令人惊讶。 - E net4