Deref coercion not working for if-expressions?

On this code:

fn main() {
    // Ok, it works
    let a: &usize = &Box::new(4);
    // It fails: error: mismatched types expected `usize`, found `Box<_>`
    let b: &usize = & (if true {Box::new(4) } else { Box::new(4) });
}

(Playpen)

Is that an intended behavior ? The same occurs with a match expression.

Even more interesting: let c = & { if true {Box::new(4) } else { Box::new(4) } }; works.
Or even let d = & { (if true {Box::new(4) } else { Box::new(4) }) };.

You may have found a bug here. Note that you can also omit the parentheses.

I can't make your example working to get a &usize, all I can get is a &Box<usize>...
Another thing that works (why ?):

let b: &usize = && (if true {Box::new(4) } else { Box::new(4) });

Is it possibly related to how scopes are treated? This will also cause an error:

let b: &usize = &{ Box::new(4) };

Looking into the Rust issue tracker, #26978 might be related.

1 Like

Yes, that's probably the same bug. Thanks !