rust-lang / rust-lang/rust

Suggest wrapping code into `fn main() {}` when encountering `let` within `main.rs`

Open
#129,786 3 comments 0 reactions 1 assignee View on GitHub

@AleksaBajat is already working on this.

Since Aug 31, 2024.

A-diagnostics T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

Code
let hello = "xyz";
Current output
error: expected item, found keyword `let`
 --> src/main.rs:1:1
  |
1 | let hello = "xyz";
  | ^^^ consider using `const` or `static` instead of `let` for global variables

error: could not compile `thing` (bin "thing") due to 1 previous error
Desired output
error: expected item, found keyword `let`
 --> src/main.rs:1:1
  |
1 | let hello = "xyz";
  | ^^^^^^^^^^^^^ consider wrapping this code within `fn main() {}`

error: could not compile `thing` (bin "thing") due to 1 previous error
Rationale and extra context

Sometimes users copy code from a crate's readme or doctests and expect it to run as is. In some cases like reqwest ^1 or sqlx ^2 it does, but in others like ours ^3 it doesn't.

In our case we are thinking of adding fn main() {} to the readme, but this doesn't solve the case where e.g. the doctests don't have it, which thanks to how rustdoc works ^4 they don't in most cases.

If the file is main.rs, fn main() {} hasn't been declared yet and let is encountered, the compiler should be able to suggest wrapping the code into fn main() {}.

Other cases

No response

Rust Version
rustc 1.82.0-nightly (1f12b9b0f 2024-08-27)
binary: rustc
commit-hash: 1f12b9b0fdbe735968ac002792a720f0ba4faca6
commit-date: 2024-08-27
host: x86_64-unknown-linux-gnu
release: 1.82.0-nightly
LLVM version: 19.1.0
Anything else?

No response

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.