在code下面,我生成一个向量,然后将其用作闭包的内容:
fn main() {
let f = {
let xs: Vec<(usize, usize)> = Vec::new();
// populate xs
move |i, j| xs[j].1 - xs[i].0
};
let x = f(1usize, 2usize);
}
为什么尽管向量是显式类型的,但代码编译失败并出现类型推断错误?
error[E0282]: type annotations needed
--> src/main.rs:5:21
|
5 | move |i, j| xs[j].1 - xs[i].0
| ^^^^^ cannot infer type
|
= note: type must be known at this point
最佳答案
[i]
Rust 中的语法来自于实现 std::ops::Index
trait .
那个特征看起来像这样:
pub trait Index<Idx>
where
Idx: ?Sized,
{
type Output: ?Sized;
fn index(&self, index: Idx) -> &Self::Output;
}
你可以实现Index
对于一个类型多次,每次用不同的类型为 Idx
范围。 Vec
通过使用 Index
的整体实现来支持尽可能多的不同索引机制:
impl<T, I> Index<I> for Vec<T>
where
I: SliceIndex<[T]>,
这适用于任何也有 SliceIndex
的类型实现,其中包括 usize
,正如您尝试使用的那样,还有范围类型,例如 Range<usize>
(例如 0..5
)和 RangeFrom<usize>
(例如 0..
)。在闭包内部,编译器不知道 Index
的哪个实现将被使用,并且每种可能性都可能有不同的 Output
类型,这就是为什么它不能在那里推断出单一类型的原因。
您可以通过注释闭包的参数来修复它:
let f = {
let xs: Vec<(usize, usize)> = Vec::new();
//
move |i: usize, j: usize| xs[j].1 - xs[i].0
};
let x = f(1, 2);
关于types - 为什么索引显式类型的向量会因类型推断错误而失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56611350/