为什么索引显式类型的向量失败并出现类型推断错误?

Lis*_*one 4 types rust

在下面的代码中,我生成一个向量,然后将其用作闭包的内容:

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);
}
Run Code Online (Sandbox Code Playgroud)

为什么尽管显式键入了向量,但代码为何无法编译并带有类型推断错误?

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
Run Code Online (Sandbox Code Playgroud)

Pet*_*all 5

[i]Rust中的语法来自实现std::ops::Indextrait

该特征看起来像这样:

pub trait Index<Idx> 
where
    Idx: ?Sized, 
{
    type Output: ?Sized;
    fn index(&self, index: Idx) -> &Self::Output;
}
Run Code Online (Sandbox Code Playgroud)

您可以Index为一个类型实现多次,每次都为Idx参数使用不同的类型。Vec通过使用以下方法的总体实现,支持尽可能多的不同索引机制Index

impl<T, I> Index<I> for Vec<T>
where
    I: SliceIndex<[T]>, 
Run Code Online (Sandbox Code Playgroud)

此方法适用于也有SliceIndex实现的任何类型,包括usize您尝试使用的实现,还包括范围类型,例如Range<usize>(eg 0..5)和RangeFrom<usize>(eg 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);
Run Code Online (Sandbox Code Playgroud)