Skip to content

Types should be inferrable across bit boolean operators #107556

Open
@tgross35

Description

@tgross35

I have not been able to find an issue documenting this (perhaps I haven't been looking for the right thing), but it is a bit surprising that type inference doesn't seem to carry across boolean operators well. Example code:

fn main() {
    let x: u8 = 100;              // setup
    let y: u32 = x.into();        // example
    let z: u32 = 1u32 | x;           // option 1
    let z: u32 = 1u32 | x.into();    // option 2
    let z: u32 = 1u32 | (x as u32);  // working solution

    println!("{y}");
}

With only option 1 enabled, we get the following:

error[[E0308]](https://doc.rust-lang.org/stable/error-index.html#E0308): mismatched types
 --> src/main.rs:6:25
  |
6 |     let z: u32 = 1u32 | x;           // option 1
  |                         ^ expected `u32`, found `u8`

So, the compiler is aware of the expected type, seems like the perfect case for into rather than a cast. However, when switching to option 2:

error[[E0284]](https://doc.rust-lang.org/stable/error-index.html#E0284): type annotations needed
 --> src/main.rs:7:27
  |
7 |     let z: u32 = 1u32 | x.into();    // option 2
  |                       -   ^^^^
  |                       |
  |                       type must be known at this point

it is unable to infer the type. Which is a bit unexpected, because true booleans operators like if true && 1u8.into() work enough that it knows there is no From<u8> for bool.

Maybe there is some restriction for why this couldn't be implemented for all types, but it would be quite handy to have for integers.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-inferenceArea: Type inferenceT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.T-typesRelevant to the types 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