reference icon indicating copy to clipboard operation
reference copied to clipboard

Document when the return type of a block expression implicitly becomes `!`

Open smarnach opened this issue 4 years ago • 4 comments

The reference currently states

The type of a block is the type of the final expression, or () if the final expression is omitted.

However, the type of this block appears to be !:

{
    loop {}
    5;
}

whereas the type of this block is i32

{
    loop {}
    5
}

So it looks like the presence of an expression of type ! changes the default type of the block from () to !.

As a side note, the doucmentation could also make clearer that "omitting the final expression" essentially means terminating the block with a semicolon.

smarnach avatar Jun 02 '21 12:06 smarnach

Thanks for opening the issue! I'm uncertain if this is a bug or not, so I figured I'd open https://github.com/rust-lang/rust/issues/85936. There are some complexities around never coercion that I do not understand.

ehuss avatar Jun 02 '21 15:06 ehuss

I think it's intentional, since otherwise { return; } would be of type (), which would be really inconvenient in if/else statements, since it would force that type on the other branch.

smarnach avatar Jun 02 '21 15:06 smarnach

Hm, yea. I don't know anything about how type checking works, but it would be great to get some documentation on this.

On the linked issue someone pointed out this comment:

https://github.com/rust-lang/rust/blob/a93699f20a433797a4b84787b9652300dd7b2ad2/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs#L654-L660

ehuss avatar Jun 03 '21 20:06 ehuss