Skip to content

diagnostics for capturing closures that are coerced to fn pointers are not great #71895

Closed
@nikomatsakis

Description

@nikomatsakis

Given this program (playground):

fn main() {
    let y = 22;
    let x: fn() = || drop(y);
}

the error message is currently:

error[E0308]: mismatched types
 --> src/main.rs:3:19
  |
3 |     let x: fn() = || drop(y);
  |            ----   ^^^^^^^^^^ expected fn pointer, found closure
  |            |
  |            expected due to this
  |
  = note: expected fn pointer `fn()`
                found closure `[closure@src/main.rs:3:19: 3:29 y:_]`

The problem here is that closures can be coerced to fn types, but only if they don't capture any variables (and this one does capture y) -- see #39817 for more details. I think that we ought to give an error like:

error[E0308]: closure cannot be forced to `fn()` type because it captures `y`
 --> src/main.rs:3:19
  |
3 |     let x: fn() = || drop(y);
  |            ----           ^ `y` captured due to use here
  |            |
  |            expected due to this
  |
  = note: closures can only be coerced to `fn` types if they do not capture any variables

Metadata

Metadata

Assignees

Labels

A-closuresArea: Closures (`|…| { … }`)A-diagnosticsArea: Messages for errors, warnings, and lintsC-enhancementCategory: An issue proposing an enhancement or a PR with one.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