rust-lang / rust-lang/rust

Type inference failing

Open
#125,329 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-inference C-bug T-types
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

I tried this code:

fn foo() -> Option<Box<u8>> {
    todo!()
}

fn bar(_: Option<&u8>) {}

fn main() {
    let mut v = vec![];
    bar(v.last().map(|x| &**x));
    v.push(foo());
}

I would expect v to have a knowable type but it's failing with this error:

error[E0282]: type annotations needed for `&T`
  --> src/main.rs:11:27
   |
11 |         bar(v.last().map(|x| &**x));
   |                           ^   --- type must be known at this point
   |
help: consider giving this closure parameter an explicit type, where the type for type parameter `T` is specified
   |
11 |         bar(v.last().map(|x: &T| &**x));
   |                            ++++

For more information about this error, try `rustc --explain E0282`.
error: could not compile `tests` (bin "tests") due to 1 previous error

It's able to infer it if we swap the lines

    v.push(foo());
    bar(v.last().map(|x| &**x));
Meta

Tried on nightly and stable

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 compiling the reproduction in src/main.rs and compare the two statement orderings shown in the report. Investigate Rust's type-inference behavior around v.last(), map, and the later push call. Done means the reported ordering infers v's type without an annotation and has regression coverage.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.