Why does indexing an explicitly typed vector fail with a type inference error?

前端 未结 1 1981
醉梦人生
醉梦人生 2021-01-19 11:24

In the code below, I generate a vector and then use it as content for a closure:

fn main() {
    let f = {
        l         


        
1条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-19 11:35

    The [i] syntax in Rust comes from implementing the std::ops::Index trait.

    That trait looks like this:

    pub trait Index 
    where
        Idx: ?Sized, 
    {
        type Output: ?Sized;
        fn index(&self, index: Idx) -> &Self::Output;
    }
    

    You can implement Index for a type multiple times, each with a different type for the Idx parameter. Vec supports as many different indexing mechanisms as possible by using a blanket implementation of Index:

    impl Index for Vec
    where
        I: SliceIndex<[T]>, 
    

    This will work for any type that also has a SliceIndex implementation, which includes usize, as you were trying to use, but also range types, like Range (e.g. 0..5) and RangeFrom (e.g. 0..). Inside the closure, the compiler doesn't know which implementation of Index is going to be used, and each possibility could have a different Output type, which is why it can't infer a single type there.

    You can fix it by annotating the arguments of the closure:

    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);
    

    0 讨论(0)
提交回复
热议问题