Skip to content

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

Description

@smarnach

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.

Activity

  1. ehuss commented on Jun 2, 2021

    @ehuss
    Contributor

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

  2. smarnach commented on Jun 2, 2021

    @smarnach
    Author

    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.

  3. ehuss commented on Jun 3, 2021

    @ehuss
    Contributor

    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

  4. added
    C-bugIncorrect statements, terminology, or rendering issues
    on Jul 16, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugIncorrect statements, terminology, or rendering issues

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions