rust-lang / rust-lang/rust

Mismatched types for a conditional containing closures inside method call

Open
#127,525 0 comments 0 reactions 1 assignee View on GitHub

@compiler-errors is already working on this.

Since Jul 9, 2024.

A-closures C-bug T-types
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

Hello! I have encountered an issue when using a conditional returning closures inside a method call - specifically, the compiler is unable to coerce closure types to Box<dyn Fn(...)->...> for a very specific case. Consider this code.

trait Foo<I : Fn() -> i16>{
    fn foo(&self, param : I) -> ();
}
struct S {}

impl Foo<Box<dyn Fn() -> i16>> for S {
    fn foo(&self, param : Box<dyn Fn() -> i16>) -> () {
        unimplemented!();
    }
}

fn main() {
    let s = S {};
    
    let cond = true;
    s.foo(if cond { //replace cond with cond==true
        Box::new(|| {42})
    }
    else {
        Box::new(|| {42})
    });
}

The above code does not compile, with an error message saying that if and else have incompatible types. When cond is replaced with cond==true, the code will compile.

This issue is very similar to an issue I submitted a while back (#126988). But only now have I found that the compiler behaves differently for different conditionals.

Also, when you enclose the type of param in another type, for example Vec, the code will compile even with just cond if-statement conditional. See adjusted code below that compiles:

trait Foo<I : Fn() -> i16>{
    fn foo(&self, param : Vec<I>) -> ();
}
struct S {}

impl Foo<Box<dyn Fn() -> i16>> for S {
    fn foo(&self, param : Vec<Box<dyn Fn() -> i16>>) -> () {
        unimplemented!();
    }
}

fn main() {
    let s = S {};
    
    let cond = true;
    s.foo(if cond {
        vec![if cond {Box::new(|| {42})} else {Box::new(|| {43})}]
    }
    else {
        vec![Box::new(|| {42})]
    });
}
Meta
rustc 1.75.0 (82e1608df 2023-12-21)
release: 1.75.0
LLVM version: 17.0.6

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.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.