In the 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
The [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>
(e.g. 0..5
) and RangeFrom<usize>
(e.g. 0..
)。在闭包内部,编译器不知道which实施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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)