Deref coercion not working for if-expressions?


#1

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.


#2

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.


#3

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) });

#4

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

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

#5

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


#6

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