Skip to content

LUB coercions can't combine unsafe fn item with safe fn item or pointer #131854

Open
@lukas-code

Description

@lukas-code

I tried this code: playground

fn safe_fn() {}
unsafe fn unsafe_fn() {}

fn lub() {
    // safe fn item + unsafe fn item
    // doesn't work
    let _ = if true { safe_fn } else { unsafe_fn };

    // safe fn ptr + unsafe fn item
    // doesn't work
    let _ = if true { safe_fn as fn() } else { unsafe_fn };

    // safe fn item + unsafe fn ptr
    // works
    let _ = if true { safe_fn } else { unsafe_fn as unsafe fn() };

    // closure + unsafe fn item
    // works
    let _ = if true { || {} } else { unsafe_fn };
}

I expected to see this happen: I expected the safe fn item and unsafe fn item to combine to an unsafe fn ptr, especially since the closure and unsafe fn item do combine to an unsafe fn ptr.

Instead, this happened:

error[E0308]: `if` and `else` have incompatible types
 --> src/lib.rs:7:40
  |
7 |     let _ = if true { safe_fn } else { unsafe_fn };
  |                       -------          ^^^^^^^^^ expected safe fn, found unsafe fn
  |                       |
  |                       expected because of this
  |
  = note: expected fn item `fn() {safe_fn}`
             found fn item `unsafe fn() {unsafe_fn}`

error[E0308]: `if` and `else` have incompatible types
  --> src/lib.rs:11:48
   |
11 |     let _ = if true { safe_fn as fn() } else { unsafe_fn };
   |                       ---------------          ^^^^^^^^^ expected safe fn, found unsafe fn
   |                       |
   |                       expected because of this
   |
   = note: expected fn pointer `fn()`
                 found fn item `unsafe fn() {unsafe_fn}`
   = note: unsafe functions cannot be coerced into safe function pointers

Meta

playground nightly

Build using the Nightly version: 1.84.0-nightly

(2024-10-16 798fb83f7d24e31b16ac)

@rustbot label A-coercions T-types

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-coercionsArea: implicit and explicit `expr as Type` coercionsC-bugCategory: This is a bug.T-typesRelevant to the types 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