rust-lang / rust-lang/rust

Type inference fails where LUB coercion succeeds

Open
#134,121 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

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

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 listed array, generic-function, and conditional-expression examples with the reported nightly toolchain using rustc --version --verbose. Compare the type-inference and LUB-coercion behavior across each symmetrical pair; the issue does not identify source files or define whether the desired outcome is a compiler change or confirmation of intended behavior.

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
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.