Closed
Description
I tried to use a struct literal as part of a condition, and got a bad error message. Here's a reduced version that fails:
pub struct Example { a: i32 }
impl Example {
fn is_pos(&self) -> bool { self.a > 0 }
}
fn one() -> i32 { 1 }
fn main() {
if Example { a: one(), }.is_pos() {
println!("Positive!");
}
}
This gives these rather poor error messages which don't align with the actual problem:
Standard Error
Compiling playground v0.0.1 (/playground)
error: struct literal body without path
--> src/main.rs:10:16
|
10 | if Example { a: one(), }.is_pos() {
| ^^^^^^^^^^^^^
|
help: you might have forgotten to add the struct literal inside the block
|
10 | if Example { SomeStruct { a: one(), } }.is_pos() {
| ^^^^^^^^^^^^ ^
error: expected one of `.`, `;`, `?`, `}`, or an operator, found `{`
--> src/main.rs:10:39
|
10 | if Example { a: one(), }.is_pos() {
| ^ expected one of `.`, `;`, `?`, `}`, or an operator
(If you remove the trailing comma inside the struct literal, it only produces the second of these two errors.)
If I change the one()
to a literal 1
, then it gives a much more useful error message:
error: struct literals are not allowed here
--> src/main.rs:10:8
|
10 | if Example { a: 1 }.is_pos() {
| ^^^^^^^^^^^^^^^^
|
help: surround the struct literal with parentheses
|
10 | if (Example { a: 1 }).is_pos() {
| ^ ^
So something about having a function call in the struct initializer breaks the diagnostic.
Meta
Tested against the
rustc --version --verbose
:
1.52.0-nightly (2021-02-12 3f5aee2d5241139d808f)
Metadata
Metadata
Assignees
Labels
Area: Messages for errors, warnings, and lintsArea: The lexing & parsing of Rust source code to an ASTCategory: This is a bug.Diagnostics: Confusing error or lint that should be reworked.Diagnostics: A diagnostic that is giving misleading or incorrect information.Diagnostics: A structured suggestion resulting in incorrect code.Diagnostics: Confusing error or lint; hard to understand for new users.Relevant to the compiler team, which will review and decide on the PR/issue.