Skip to content

Give a better error message for functions in struct { ... } #76421

Closed
@jyn514

Description

@jyn514

Thought of this while reading https://fasterthanli.me/articles/i-am-a-java-csharp-c-or-cplusplus-dev-time-to-do-some-rust (thank you @fasterthanlime !). Currently putting a function in a struct definition is a syntax error without much hint of what went wrong (playground):

struct S {
    field: usize,
    
    fn do_something() {
    }
}
error: expected identifier, found keyword `fn`
 --> src/lib.rs:4:5
  |
4 |     fn do_something() {
  |     ^^ expected identifier, found keyword

error: expected `:`, found `do_something`
 --> src/lib.rs:4:8
  |
4 |     fn do_something() {
  |        ^^^^^^^^^^^^ expected `:`

error: aborting due to 2 previous errors

Instead it should say something like

error: functions are not allowed in struct definitions
 --> src/lib.rs:4:5
  |
4 |     fn do_something() {
  |     ^^^^^^^^^^^^^^^^^^^
  = help: unlike in C++, Java, and C#, functions are declared in `impl` blocks
  = help: see https://doc.rust-lang.org/book/ch05-03-method-syntax.html for more information

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-feature-requestCategory: A feature request, i.e: not implemented / a PR.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