Skip to content

Invalid cast error when trying to cast a closure to a function pointer should mention captured variables #128078

Closed
@divergentdave

Description

@divergentdave

Code

fn main() {
    let captured = "x";
    let closure = || { captured.to_string() };
    let fn_ptr = closure as fn() -> String;
    let _ = fn_ptr();
}

Current output

error[E0605]: non-primitive cast: `{closure@src/main.rs:3:19: 3:21}` as `fn() -> String`
 --> src/main.rs:4:18
  |
4 |     let fn_ptr = closure as fn() -> String;
  |                  ^^^^^^^^^^^^^^^^^^^^^^^^^ invalid cast

For more information about this error, try `rustc --explain E0605`.
error: could not compile `playground` (bin "playground") due to 1 previous error

Desired output

error[E0605]: non-primitive cast: `{closure@src/main.rs:3:19: 3:21}` as `fn() -> String`
 --> src/main.rs:4:18
  |
4 |     let fn_ptr = closure as fn() -> String;
  |                  ^^^^^^^^^^^^^^^^^^^^^^^^^ invalid cast
help: this closure cannot be cast to a function pointer because it captures a variable
  |
2 |     let captured = "x";
  |         ^^^^^^^- captured outer variable
3 |     let closure = || { captured.to_string() }; 
  |                   -- captured by this Fn closure

For more information about this error, try `rustc --explain E0605`.
error: could not compile `playground` (bin "playground") due to 1 previous error

Rationale and extra context

I forgot a closure was capturing a variable while I was refactoring and setting up an array of function pointers. I had to double check the reference to figure out what the error was referring to.

Other cases

No response

Rust Version

rustc 1.79.0 (129f3b996 2024-06-10)
binary: rustc
commit-hash: 129f3b9964af4d4a709d1383930ade12dfe7c081
commit-date: 2024-06-10
host: x86_64-unknown-linux-gnu
release: 1.79.0
LLVM version: 18.1.7

Anything else?

No response

Metadata

Metadata

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

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions