rust-lang / rust-lang/rust

LUB coercions works for a function but fails for a closure

Open
#132,643 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-closures A-coercions A-diagnostics C-bug D-confusing T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

I tried the following code (playground), following the examples for LUB coercion in the Reference, chapter 10.7.

The closure does not compile

    let clo = || {
        if true {
            let x: *mut i32 = &mut 1;
            x
        } else if false {
            let x: &i32 = &1;
            x
        } else {
            let x: &mut i32 = &mut 1;
            x
        }
    };
    let _: *const i32 = clo();

with the error:

error[E0308]: `if` and `else` have incompatible types

A similar function does compile:

fn f() -> *const i32 {
    if true {
        let x: *mut i32 = &mut 1;
        x
    } else if false {
        let x: &i32 = &1;
        x
    } else {
        let x: &mut i32 = &mut 1;
        x
    }
}

According to the Reference, I expected that either both the closure and the function compiles or neither of them.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by compiling the closure and function examples from the issue in the linked Rust Playground, then compare their LUB coercion behavior with the Reference's type-coercion examples. Trace the compiler's handling of closure return types and conditional expressions. Done means the behavior matches the documented rules, with an appropriate regression test for the reproduced case.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.