Skip to content

cannot infer type when expression is logically negated in closure #106138

Description

@Isopod

Hi! I’m pretty new to Rust, but I think I just encountered a bug in the compiler.

For some reason, Rust cannot “infer” the type of !a[i] in this code:

pub fn myfunction(x: &Vec<bool>) {
    let closure = |i, a: &Vec<bool>| { !a[i] };
    closure(0, x);
}
error[E0282]: type annotations needed
 --> main.rs:2:40
  |
2 |     let closure = |i, a: &Vec<bool>| { !a[i] };
  |                                        ^^^^^ cannot infer type

error: aborting due to previous error

For more information about this error, try `rustc --explain E0282`.

But when you replace !a[i] with just a[i], then it compiles without error. So the error only occurs when there is a logical negation.

While narrowing this down, I also noticed that the error message appears to be a bit misleading: It looks like the compiler actually fails to infer the type of i, not !a[i], as the error goes away when I add a type annotation for i. Here is a more elaborate example, combining all of my three test cases:

pub fn myfunction(x: &Vec<bool>) {
    let one = |i, a: &Vec<bool>| {
        a[i]  // ok
    };
    let two = |i, a: &Vec<bool>| {
        !a[i] // cannot infer type
    };
    let three = |i: usize, a: &Vec<bool>| {
        !a[i] // ok
    };

    one(0, x);
    two(0, x);
    three(0, x);
}

fn main() {
}

Run it on Rust Playground

Reproduces on Stable, Beta and Nightly.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

A-closuresArea: Closures (`|…| { … }`)A-inferenceArea: Type inferenceC-bugCategory: This is a bug.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions