Weird error message when a struct literal is used in a condition of an if statement
Open
@chenyukang is already working on this.
Since Sep 4, 2026.
A-diagnostics
A-parser
D-terse
T-compiler
- Dominant language
- Rust
- Stars
- 119k
- Forks
- 16.1k
- PR merge metrics
- PR metrics pending
Description
Code
fn main() {
let foo = Foo { x: 3 };
let x = 3;
let y = if foo == Foo { x } { x } else { 0 };
}
#[derive(Eq, PartialEq)]
struct Foo {
x: u32,
}
Current output
error: expected one of `.`, `;`, `?`, `else`, or an operator, found `{`
--> src/main.rs:4:33
|
4 | let y = if foo == Foo { x } { x } else { 0 };
| ^ expected one of `.`, `;`, `?`, `else`, or an operator
error: could not compile `err` (bin "err") due to 1 previous error
Desired output
In some contexts, the compiler knows that a struct literal can be ambiguous and use parenthesis. But in this context, it does not know which curly brace is for the struct literal. There must be at least a help message that a struct literal can be ambiguous.
Rationale and extra context
No response
Other cases
If I slightly modify the code like below, it gives me a much better error message.
fn main() {
let foo = Foo { x: 3 };
let x = 3;
let y = if foo == Foo { x: 3 } { x } else { 0 };
}
#[derive(Eq, PartialEq)]
struct Foo {
x: u32,
}
error:
error: struct literals are not allowed here
--> src/main.rs:4:23
|
4 | let y = if foo == Foo { x: 3 } { x } else { 0 };
| ^^^^^^^^^^^^
|
help: surround the struct literal with parentheses
|
4 | let y = if foo == (Foo { x: 3 }) { x } else { 0 };
| + +
It seems like the compiler uses `:` to figure out whether it's a struct literal or not.
Rust Version
rustc 1.90.0 (1159e78c4 2025-09-14)
binary: rustc
commit-hash: 1159e78c4747b02ef996e55082b704c09b970588
commit-date: 2025-09-14
host: x86_64-unknown-linux-gnu
release: 1.90.0
LLVM version: 20.1.8
Anything else?
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.
Assessment
This issue has not been assessed yet.