Nested coercion in array results in type mismatch, inconsistent with `if` and `match`.
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 119k
- Forks
- 16.1k
- PR merge metrics
- PR metrics pending
Description
I tried this code:
fn foo() {}
fn bar() {}
fn main() {
let _ = [foo, if false { bar } else { foo }];
}
I expected to see this happen: It compiles, like in if or match.
fn foo() {}
fn bar() {}
fn main() {
let _ = if false {
foo
} else {
if false {
bar
} else {
foo
}
};
let _ = match 1 {
2 => foo,
_ => if false {
bar
} else {
foo
},
};
}
Instead, this happened: type mismatch when trying to coerce bar into foo.
The cause: check_expr_array uses a type variable as the expectation during element typecking but the type variable is unified with the first element's type during coercion.
https://github.com/rust-lang/rust/blob/9b1a30e5e69e1537ef6eb6eb829eb47075206dea/compiler/rustc_hir_typeck/src/expr.rs#L1818-L1828
It should use try_structurally_resolve_and_adjust_for_branches on the element expectation as if and match do, which turns the expectation into NoExpectation if the expected_ty is a true type variable.
However, this simple fix can break some other code.
Recursive tuple coercion can fix this case. But it's complicated.
Meta
rustc --version --verbose:
1.91.0-nightly
(2025-08-06 7d82b83ed57d188ab3f2)
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Reproduce the issue with the Rust snippets in the report, then inspect check_expr_array in compiler/rustc_hir_typeck/src/expr.rs at the cited lines. Compare its element expectation handling with try_structurally_resolve_and_adjust_for_branches in if and match checking. Done means nested coercion in array elements compiles consistently without breaking the related cases noted in the issue.
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
- Mostly clear
- Newbie friendliness
- 35/100