此代码编译:
#[derive(Debug, Default)]
struct Example;
impl Example {
fn some_method(&self) {}
}
fn reproduction() -> Example {
let example = Default::default();
// example.some_method();
example
}
如果添加回注释行,将导致错误:
error[E0282]: type annotations needed
--> src/lib.rs:10:5
|
9 | let example = Default::default();
| ------- consider giving `example` a type
10 | example.some_method();
| ^^^^^^^ cannot infer type
|
= note: type must be known at this point
为什么添加此方法调用会导致类型推断失败?
我看到了这两个问题:
- How does Rust's type inference work across multiple statements?
- How does Rust infer resultant types from From::<>::from()?
米尔纳的印地语版本是modified.后一个问题有an answer个,将Rust的类型推断描述为一个方程组.Another answer明确指出"Rust中的类型信息可以向后流动".
将这些知识应用于这种情况,我们已经:
-
example
是?E
型 -
?E
必须有一个名为some_method
的方法 -
?E
美元被退回 - 返回类型为
Example
向后看,人类很容易看出?E
一定是Example
.我能看到的和编译器能看到的之间的差距在哪里?