rust-lang / rust-lang/rust

failed type inference when indexing vec-of-vec in closure

Open
#139,334 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-diagnostics A-inference T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

I tried this code:

fn main() {
    let v: Vec<Vec<u64>> = vec![vec![7]];
    let f = |x, y| v[x][y];
}

I expected to see this happen: code compiles successfully

Instead, this happened:

Compiling playground v0.0.1 (/playground)
error[[E0282]](https://doc.rust-lang.org/stable/error_codes/E0282.html): type annotations needed
 --> src/main.rs:3:20
  |
3 |     let f = |x, y| v[x][y];
  |                    ^^^^ cannot infer type

The strange thing is that type inference for x and y work fine, it's the intermediate temporary's type that can't be inferred.

This snippet works:

fn use_closure(_f: impl Fn(usize, usize) -> u64) {}

fn main() {
    let v: Vec<Vec<u64>> = vec![vec![7]];
    let f = |x, y| -> u64 { 
        let tmp: &Vec<u64> = &v[x];
        tmp[y]
    };
    use_closure(f);
}
Meta

Version: happens with both 1.86.0 stable and 1.88.0-nightly (2025-04-02 d5b4c2e4f19b6d703737)

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the closure example in src/main.rs and compare it with the working version that explicitly types the intermediate reference. Trace the compiler's type inference for nested indexing and identify why the temporary type is not inferred. Done means the original snippet compiles without annotations and the regression is covered by an appropriate compiler test.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.