Allow returning an impl trait in a Result?

Below code does not compile.

fn foo()->Result<impl Fn(&usize),usize>{
    return Err(0);   
    Ok(|a|{})
}

This would be very useful in patterns where you initialize a system, and then pass the system to a closure that can then be called many times. It would allow the initialization of the system to fail and allow the user to use the question mark operator.

Update this compiles:

fn foo()->Result<impl Fn(&usize),usize>{
    return Err(0);

    let f:for<'r> fn(&'r usize) -> _=|a|{
        
    };
    Ok(f)
}

but not this:

fn foo()->Result<impl Fn(&usize),usize>{
    return Err(0);
    let k=0;
    let f:for<'r> fn(&'r usize) -> _=|a|{
        dbg!(k);
    };
    Ok(f)
}

This works:

fn foo() -> Result<impl Fn(&usize), usize> {
    return Err(0);
    let k = 0;
    Ok(|a: &usize| {
        dbg!(k);
    })
}

The problem isn't to do with impl Trait inside a Result, it's to do with limited HRTB inference for closures.

1 Like