Skip to content

Type inference fails where LUB coercion succeeds #134121

Open
@purplesyringa

Description

@purplesyringa

This is probably a known effect, but I'd like to get confirmation that this is intended behavior or a known bug. It sure caught me by surprise.

I tried this code:

let a1: _ = [b"a", b"a" as &[u8]];
let b1: _ = [b"a" as &[u8], b"a"];

let a2: [_; 2] = [b"a", b"a" as &[u8]];
let b2: [_; 2] = [b"a" as &[u8], b"a"];

let a3: [&[u8]; 2] = [b"a", b"a" as &[u8]];
let b3: [&[u8]; 2] = [b"a" as &[u8], b"a"];

fn unify<T>(_x: T, _y: T) {}
unify(b"a", b"a" as &[u8]); // a4
unify(b"a" as &[u8], b"a"); // b4

if true { b"a" } else { b"a" as &[u8] }; // a5
if true { b"a" as &[u8] } else { b"a" }; // b5

I expected to see this happen: Each pair of lines is symmetrical, so intuitively, either they should both compile or both fail typeck.

Instead, this happened:

  • a1 and b1 both compile
  • a2 fails to compile, b2 compiles
  • a3 and b2 both compile
  • a4 fails to compile, b4 compiles
  • a5 and b5 both compile

The reason is that in cases 1, 3, 5, LUB coercion is used, and in cases 2 and 4, a more generic type inference mechanism is used (I think). I can kind of see why a4 needs to fail compilation, but a2 failing is extremely counterintuitive.

Meta

rustc --version --verbose:

rustc 1.84.0-nightly (1e4f10ba6 2024-10-29)
binary: rustc
commit-hash: 1e4f10ba6476e48a42a79b9f846a2d9366525b9e
commit-date: 2024-10-29
host: x86_64-unknown-linux-gnu
release: 1.84.0-nightly
LLVM version: 19.1.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-coercionsArea: implicit and explicit `expr as Type` coercionsA-inferenceArea: Type inferenceC-bugCategory: This is a bug.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