Skip to content

If-else type checking fails with trait method calls and closures #126988

Closed
@marmac02

Description

@marmac02

I've encountered the following issue related to mismatch of types when using closures together with a conditional inside a call to a trait method. It occurs in the cases like the one below:

Code

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

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

fn main() {
    let s = S {};
    
   // This call does not compile: error[E0308]: `if` and `else` have incompatible types
    s.foo(if true {
                Box::new(|| {42})} 
            else {
                Box::new(|| {42})
         });

    //This compiles (without the if-statement)
    s.foo(Box::new(|| {42}));
}

Also if you replace param : I with param : Box<dyn Fn() -> i32> in foo function signature inside Foo declaration, the call s.foo containing if-statement compiles too.
To me this seems to be an inconsistent behavior, but I'm not sure if it counts as a bug or is some design decision but I wasn't able to verify.

Meta

rustc 1.75.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-discussionCategory: Discussion or questions that doesn't represent real issues.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions