-
Notifications
You must be signed in to change notification settings - Fork 13.6k
Closed
Labels
A-diagnosticsArea: Messages for errors, warnings, and lintsArea: Messages for errors, warnings, and lintsT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.Relevant to the compiler team, which will review and decide on the PR/issue.
Description
When running the following Rust code:
fn my_fn(event: &Event<'_>) {}
struct Event<'a>(&'a ());
fn main() {
const ptr: &fn(&Event<'_>) = &my_fn as _;
}
The cast using as _
should succeed, or the compiler should give a clearer reason for rejection if it is truly invalid. Since the types are compatible under HRLB, i guess this coercion should ideally be allowed.
The issue arises from using a reference before the function pointer. (It works when removed)
However, the compiler currently emits the following error:
error[E0605]: non-primitive cast: `&for<'a, 'b> fn(&'a Event<'b>) {my_fn}` as `&for<'a, 'b> fn(&'a Event<'b>)`
--> src/main.rs:8:43
|
8 | const ptr: &fn(&Event<'_>) = &my_fn as _;
| ^^^^^^^^^^^^^^^ an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object
This happens on stable, beta, and nightly Rust.
Workaround:
fn my_fn(event: &Event<'_>) {}
struct Event<'a>(&'a ());
const fn force<F: Fn(&Event<'_>)>(x: F) -> F {
x
}
fn main() {
const ptr: &fn(&Event<'_>) = &force(|event| { my_fn(event) });
}
Thanks to @_madfrog on Discord for the help
Metadata
Metadata
Assignees
Labels
A-diagnosticsArea: Messages for errors, warnings, and lintsArea: Messages for errors, warnings, and lintsT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.Relevant to the compiler team, which will review and decide on the PR/issue.