Skip to content

Using ? in a constant offers a confusing error message #156200

@shepmaster

Description

@shepmaster

Code

fn can_fail() -> Result<(), ()> { Ok(()) }

fn main() -> Result<(), ()> {
    const foo = can_fail()?;
    Ok(())
}

Current output

error[E0572]: return statement outside of function body
 --> src/main.rs:4:27
  |
4 |     const foo = can_fail()?;
  |                           ^

Desired output

error[E0572]: the `?` operator may not be used to return while defining a constant
 --> src/main.rs:4:27
  |
4 |     const foo = can_fail()?;
  |                           ^

Rationale and extra context

This is confusing for two reasons:

  1. The thing pointed at is not a literal return statement. Presumably there is a return-like-thing in the desugared code.
  2. The thing pointed at is inside a function body. It just happens to also be inside a constant.

Rust Version

rustc 1.95.0 (59807616e 2026-04-14)
binary: rustc
commit-hash: 59807616e1fa2540724bfbac14d7976d7e4a3860
commit-date: 2026-04-14
host: aarch64-apple-darwin
release: 1.95.0
LLVM version: 22.1.2
rustc 1.97.0-nightly (913e4bea8 2026-04-22)
binary: rustc
commit-hash: 913e4bea83424658d76712fee9c52452a3a9ef0e
commit-date: 2026-04-22
host: aarch64-apple-darwin
release: 1.97.0-nightly
LLVM version: 22.1.2

Anything else?

See also #105242

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions