rust-lang / rust-lang/rust

Applying a method to an erroring arithmetic expression in closure leads to vauge error

Open
#142,320 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Code
fn main() {
    let mut q: &dyn Fn(_) -> _ = &|_: usize| 10_u8;
    let mut q_tmp;
    let x = 20_i16;
    q_tmp = move |a| (a + x).clamp(0, 1);
    q = &q_tmp;
}
Current output
--> src/main.rs:5:22
  |
5 |     q_tmp = move |a| (a + x).clamp(0, 1);
  |                      ^^^^^^^ cannot infer type
Desired output
error[E0277]: cannot add `i16` to `usize`
 --> src/main.rs:5:25
  |
5 |     q_tmp = move |a| (a + x).clamp(0, 1);
  |                         ^ no implementation for `usize + i16`
  |
  = help: the trait `Add<i16>` is not implemented for `usize`
  = help: the following other types implement trait `Add<Rhs>`:
            `&usize` implements `Add<usize>`
            `&usize` implements `Add`
            `usize` implements `Add<&usize>`
            `usize` implements `Add`
Rationale and extra context

This is very confusing when the contained expression is much more complicated than adding two numbers.

Other cases

Rust Version
rustc 1.86.0 (05f9846f8 2025-03-31)
binary: rustc
commit-hash: 05f9846f893b09a1be1fc8560e33fc3c815cfecb
commit-date: 2025-03-31
host: x86_64-unknown-linux-gnu
release: 1.86.0
LLVM version: 19.1.7

(also tested on the latest nightly on the playground)
Anything else?

No response

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

Reproduce the example in src/main.rs with the reported rustc 1.86.0 toolchain and compare the current and desired diagnostics. Trace how this closure expression is diagnosed, then ensure the output identifies the incompatible usize + i16 operation and preserves the relevant source location.

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.