Skip to content

Coercion from non-capturing closure to fn ptr fails when return type is ! #66738

Open
@RalfJung

Description

@RalfJung

Usually, non-capturing closures can be coerced to fn ptrs. But somehow that seems to fail when the return type is !:

fn magic<R, F: FnOnce() -> R>(f: F) -> F { f }

fn main() {
    let f1 = magic(|| {}) as fn() -> (); // works fine
    let f2 = magic(|| loop {}) as fn() -> !; // errors
}

The error is

error[E0605]: non-primitive cast: `[closure@src/main.rs:5:21: 5:31]` as `fn() -> !`
 --> src/main.rs:5:14
  |
5 |     let f2 = magic(|| loop {}) as fn() -> !;
  |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: an `as` expression can only be used to convert between primitive types. Consider using the `From` trait

This fails even on nightly, where ! should be stable as a type.

Curiously, this works:

let f2: fn() -> ! = || loop {};

Cc @Centril

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-closuresArea: Closures (`|…| { … }`)A-coercionsArea: implicit and explicit `expr as Type` coercionsC-bugCategory: This is a bug.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