Skip to content

Bad diagnostic: "error: struct literal body without path"Β #82051

Closed
@porglezomp

Description

@porglezomp

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!");
    }
}

Playground link.

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

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-parserArea: The lexing & parsing of Rust source code to an ASTC-bugCategory: This is a bug.D-confusingDiagnostics: Confusing error or lint that should be reworked.D-incorrectDiagnostics: A diagnostic that is giving misleading or incorrect information.D-invalid-suggestionDiagnostics: A structured suggestion resulting in incorrect code.D-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.T-compilerRelevant to the compiler 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